package cn.gzjp.modules.logis.web.api.web;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.gzjp.common.baidu.AsrMain;
import cn.gzjp.common.baidu.MP3ConvertPCM;
import cn.gzjp.common.config.ConfigUtils;
import cn.gzjp.common.config.Global;
import cn.gzjp.common.constant.AppIdType;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.utils.*;
import cn.gzjp.common.utils.pay.Sha1Util;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.gas.entity.GasRecharge;
import cn.gzjp.modules.gas.entity.GasScore;
import cn.gzjp.modules.gas.service.AliyunSms;
import cn.gzjp.modules.gas.service.GasRechargeService;
import cn.gzjp.modules.gas.service.GasScoreService;
import cn.gzjp.modules.gas.service.WxMyPayService;
import cn.gzjp.modules.it.api.bean.CommonJson;
import cn.gzjp.modules.it.entity.Member;
import cn.gzjp.modules.logis.entity.*;
import cn.gzjp.modules.logis.service.*;
import cn.gzjp.modules.logis.web.api.vo.*;
import cn.gzjp.modules.wx.entity.WxMpAccount;
import cn.gzjp.modules.wx.service.WxMpAccountService;
import cn.gzjp.modules.wx.service.WxService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baidu.aip.ocr.AipOcr;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


/**
 * 微信小程序用户接口
 */
@Controller("logisController")
@Api(value = "智慧物流业务接口", description = "智慧物流业务接口")
@RequestMapping("${frontPath}/logis")
public class LogisController extends BaseController implements Serializable {

    @Autowired
    private WxService wxService;
    @Autowired
    private WxMpAccountService wxMpAccountService;
    @Autowired
    private LogisUserService logisUserService;
    @Autowired
    private LogisDeliveryService logisDeliveryService;
    @Autowired
    private GasScoreService gasScoreService;
    @Autowired
    private GasRechargeService gasRechargeService;
    @Autowired
    private LogisShareFriendService logisShareFriendService;
    @Autowired
    private LogisCarService logisCarService;
    @Autowired
    private LogisQuestionService logisQuestionService;
    @Autowired
    private LogisDeliveryLogService logisDeliveryLogService;


    /**
     * 登陆接口
     */
    @ApiOperation(value = "用户登录新(返回的是sessionKey，要获得openid请接着调用info接口)")
    @RequestMapping(value = "login", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "code", value = "code", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "shareOpenid", value = "分享者openid，没有的话传空串", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "appId", value = "appId(用于区分不同小程序)", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String login(String code, String shareOpenid, String appId) {
        CommonJson result = new CommonJson();
        log.info("智慧物流小程序用户微信登录 code=" + code + "|shareOpenid=" + shareOpenid + "|appId=" + appId);
        if (StrUtil.isEmptyOrUndefined(code)) {
            result.setMsg("code不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(appId)) {
            result.setMsg("appId不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        try {
            WxMaJscode2SessionResult session = wxService.getWxMaService(appId).getUserService().getSessionInfo(code);
            String openid = session.getOpenid();
            String unionId = session.getUnionid();
            log.info("openid=" + openid);
            log.info("unionid=" + session.getUnionid());
            if (StringUtils.isNotBlank(openid)) {
                LogisUser user = logisUserService.get(openid);
                //log.info("user=" + user);
                if (user == null) {
                    user = new LogisUser();
                    user.setId(openid);
                    user.setRegistTime(new Date());
                    user.setBalance(new BigDecimal("0"));
                    user.setScoreTotal(0);
                    user.setShouhuoNum(0);
                    user.setJiaocheNum(0);
                    user.setJiedanNum(0);
                    user.setFriendNum(0);
                    user.setFleetNum(0);
                    user.setScoreTotal(0);//默认0积分
                    user.setCreditTotal(100);//默认100信用积分
                    user.setIncomeTotal(new BigDecimal(0));
                    user.setCommissionTotal(new BigDecimal(0));
                    user.setStatus(1);//1白名单
                    user.setAppId(appId);
                    logisUserService.save(user);//新增用户
                    log.info("用户不存在，创建");
                    if (!StrUtil.isBlankOrUndefined(shareOpenid)) {
                        user.setShareOpenid(shareOpenid);//设置推荐人
                        logisUserService.save(user);
                        LogisUser shareUser = logisUserService.get(shareOpenid);
                        LogisShareFriend shareFriend = new LogisShareFriend();//记录好友记录
                        if (AppIdType.PARTNER.equals(appId)) {//车队
                            shareUser.setFleetNum(shareUser.getFleetNum() + 1);
                            shareUser.setFriendNum(shareUser.getFriendNum() + 1);//设置推荐人好友+1
                            shareFriend.setType(1);
                        } else {
                            shareUser.setFriendNum(shareUser.getFriendNum() + 1);//设置推荐人好友+1
                            shareFriend.setType(0);//好友
                        }
                        logisUserService.save(shareUser);
                        shareFriend.setUnionId(shareUser.getUnionId());
                        shareFriend.setOpenid(openid);
                        shareFriend.setFriendOpenid(shareOpenid);
                        logisShareFriendService.save(shareFriend);
                    }
                }
                if (StrUtil.isBlank(user.getAppId())) {
                    user.setAppId(appId);
                    logisUserService.save(user);//更新用户appId
                }
                if (StrUtil.isNotBlank(unionId) && StrUtil.isBlank(user.getUnionId())) {
                    user.setUnionId(unionId);
                    logisUserService.save(user);//更新用户
                }
            }
            log.info("openid=" + openid + "|sessionKey=" + session.getSessionKey());
            result.setData(session.getSessionKey());
            //log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return e.toString();
        }
    }


    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */

    @ApiOperation(value = "用户信息获取(新接口,后台可自动获取昵称和头像)")
    @RequestMapping(value = "userInfo", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "sessionKey", value = "会话密钥", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "encryptedData", value = "消息密文", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "iv", value = "加密算法的初始向量", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "appId", value = "appId(用于区分不同小程序)", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String userInfo(String sessionKey, String encryptedData, String iv, String appId) {
        CommonJson result = new CommonJson();
        log.info("智慧物流小程序用户获取用户信息 sessionKey=" + sessionKey + "|encryptedData=" + encryptedData + "|iv=" + iv + "|appId=" + appId);
        // 解密用户信息
        WxMaUserInfo userInfo = this.wxService.getWxMaService(appId).getUserService().getUserInfo(sessionKey, encryptedData, iv);
        if (userInfo == null) {
            result.setMsg("小程序获取用户信息失败");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(appId)) {
            result.setMsg("appId不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisUser user = logisUserService.get(userInfo.getOpenId());
        if (user == null) {
            result.setMsg("请先调用登录接口");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        String unionId = userInfo.getUnionId();
        log.info("unionId=" + unionId);
        if (StringUtils.isNotBlank(userInfo.getNickName())) {
            user.setNickName(StringUtils.filterWxNickName(userInfo.getNickName()));
        }
        user.setHeadImg(userInfo.getAvatarUrl());//用户头像
        if (StrUtil.isNotBlank(unionId) && StrUtil.isBlank(user.getUnionId())) {
            user.setUnionId(unionId);
        }
        logisUserService.save(user);//新增用户
        if (AppIdType.DRIVER.equals(appId)) {//司机
            LogisCar car = logisCarService.get(userInfo.getOpenId());
            user.setCarStatus(-1);
            user.setDriverStatus(-1);
            user.setRoadCount(0);
            if (car != null) {
                user.setCarStatus(car.getCarStatus());
                user.setDriverStatus(car.getDriverStatus());
            }
            LogisCarRoad search = new LogisCarRoad();
            if (StringUtils.isNotBlank(userInfo.getOpenId())) {
                search.setOpenid(userInfo.getOpenId());
            }
            List<LogisCarRoad> roads = logisCarRoadService.findList(search);
            if (roads != null && roads.size() > 0) {
                user.setRoadCount(roads.size());
                user.setFirstRoad(roads.get(0));
            }
        }
        result.setData(user);
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 解密获取用户手机号
     *
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @param openid
     * @return
     */
    @ApiOperation(value = "解密获取用户手机号")
    @RequestMapping(value = "userPhone", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "sessionKey", value = "会话密钥", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "encryptedData", value = "消息密文", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "iv", value = "加密算法的初始向量", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String userPhone(String sessionKey, String encryptedData, String iv, String openid) {
        CommonJson result = new CommonJson();
        log.info("(司机端)解密获取用户手机号 sessionKey=" + sessionKey + "|encryptedData=" + encryptedData + "|iv=" + iv + "|openid=" + openid);
        // 解密手机号信息
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid参数不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        UserPhone userPhone = this.wxService.getUserPhone(sessionKey, encryptedData, iv);
        if (userPhone == null) {
            result.setMsg("小程序解密用户手机号失败");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StringUtils.isNotBlank(userPhone.getPhoneNumber())) {
            LogisUser logisUser = logisUserService.get(openid);
            logisUser.setMobile(userPhone.getPhoneNumber());
            logisUserService.save(logisUser);
        }
        result.setData(userPhone);
        // log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    Map<String, Date> sendCodeMap = new HashMap<String, Date>();
    Map<String, String> mobileCodeMap = new HashMap<String, String>();

    /**
     * 下发短信验证码
     *
     * @param mobile
     * @return
     */
    @ApiOperation(value = "验证码获取")
    @RequestMapping(value = "sendCode", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String sendCode(String mobile) {
        CommonJson result = new CommonJson();
        log.info("智慧物流获取验证码 mobile=" + mobile);
        if (StrUtil.isEmptyOrUndefined(mobile)) {
            result.setMsg("mobile参数不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (mobile.length() != 11) {
            result.setMsg("手机号长度不正确");
            result.setCode(2);
            return this.mapper.toJson(result);
        }
        Date sendDate = sendCodeMap.get(mobile);
        if (sendDate != null && DateUtils.addMinute(sendDate, 3)
                .after(new Date())) {//3分钟还没到期
            result.setCode(3);
            ;
            result.setMsg("验证码已发送，3分钟内有效");
            ;
            return this.mapper.toJson(result);
        }

        // 随机数的生成
        String randNum = StringUtil.getRandNum(4);
        try {
            AliyunSms.sendSms("百灵智慧物流", mobile, randNum);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        result.setData(randNum);
        mobileCodeMap.put(mobile, randNum);
        sendCodeMap.put(mobile, new Date());
        //log.info("返回给小程序数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 验证短信验证码
     *
     * @param mobile
     * @param authCode
     * @return
     */
    @ApiOperation(value = "验证码验证")
    @RequestMapping(value = "verifyCode", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "authCode", value = "验证码", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String verifyCode(String mobile, String authCode, String openid) {
        CommonJson result = new CommonJson();
        log.info("智慧物流验证短信验证码 mobile=" + mobile + "|验证码=" + authCode);
        if (StrUtil.isEmptyOrUndefined(mobile) || StrUtil.isEmptyOrUndefined(authCode)) {
            result.setMsg("参数不能为空");
            result.setCode(1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (mobile.length() != 11) {
            result.setMsg("手机号长度不正确");
            result.setCode(2);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }

        String randNum = mobileCodeMap.get(mobile);
        if ("00000".equals(authCode.trim()) || StringUtils.isNotBlank(randNum) && authCode.trim().equals(randNum)) {
            LogisUser user = logisUserService.get(openid);
            user.setMobile(mobile);
            logisUserService.save(user);
            result.setCode(0);
            result.setMsg("验证成功");
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        } else {
            result.setCode(3);
            result.setMsg("验证码输入有误");
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
        }
        return this.mapper.toJson(result);
    }

    /**
     * 更新用户信息
     *
     * @return
     */
    @ApiOperation(value = "更新用户信息")
    @RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "type", value = "用户类型(1工厂与货主 2司机 3专线合伙人)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "realName", value = "真实姓名", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "carInfo", value = "车辆信息(针对司机)", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String updateUserInfo(String mobile, String type, String openid, String realName, String carInfo) {
        CommonJson result = new CommonJson();
        log.info("智慧物流更新用户信息 mobile=" + mobile + "|type=" + type + "|openid=" + openid + "|realName=" + realName + "|carInfo=" + carInfo);
        LogisUser user = logisUserService.get(openid);
        if (StringUtils.isNotBlank(mobile)) {
            user.setMobile(mobile);
        }
        if (StringUtils.isNotBlank(type)) {
            user.setType(type);
        }
//        if (StringUtils.isNotBlank(role)) {
//            user.setRole(role);
//        }
        if (StringUtils.isNotBlank(realName)) {
            user.setRealName(realName);
        }
        if (StringUtils.isNotBlank(carInfo)) {
            user.setCarInfo(carInfo);
        }
        logisUserService.save(user);
        result.setData(user);
        //log.info("返回给小程序数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 个人信息
     */
    @ApiOperation(value = "个人信息")
    @RequestMapping(value = "myInfo", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String myInfo(String openid) {
        CommonJson result = new CommonJson();
        log.info("智慧物流个人信息 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisUser user = logisUserService.get(openid);
        result.setData(user);
        // log.info("返回微信小程序" + mapper.toJson(result));


        GasRecharge search = new GasRecharge();
        if (StrUtil.isNotBlank(user.getUnionId())) {
            search.setUnionId(user.getUnionId());
        } else {
            search.setOpenid(user.getId());
        }
        List<GasRecharge> rewards = this.gasRechargeService.findList(search);
        BigDecimal balance = new BigDecimal("0");
        for(GasRecharge recharge:rewards){
            balance = balance.add(recharge.getAmount());
        }
        if(balance.intValue()>0){
            user.setBalance(balance);
            logisUserService.save(user);//更新用户余额
        }
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "新增发货")
    @RequestMapping(value = "addDelivery", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startProvince", value = "发货省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startCity", value = "发货城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startDistrict", value = "发货区", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startAddress", value = "发货详细地址", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endProvince", value = "目的地省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endCity", value = "目的地城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endDistrict", value = "目的地区", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endAddress", value = "目的地详细地址", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "distance", value = "距离", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "goodsName", value = "货物名称", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "estimateWeight", value = "货物重量(预估)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "estimateVolume", value = "货物体积(预估)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "wholeCar", value = "是否整车", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "loadTime", value = "装车时间(yyyy-mm-dd HH:mm:ss)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "loadTimeText", value = "装车时间(中文描述)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "remarks", value = "备注", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "picPaths", value = "上传后的图片路径", dataType = "String[]", paramType = "form", required = true),
            @ApiImplicitParam(name = "startLng", value = "开始经度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startLat", value = "开始纬度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endLng", value = "目的地经度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endLat", value = "目的地纬度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "ysxy", value = "运输协议", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "hwbx", value = "货物保险额(金额)", dataType = "int", paramType = "form", required = true),
            @ApiImplicitParam(name = "hwbxText", value = "货物保险额(文字描述)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "leaveMsg", value = "给司机留言", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "appId", value = "appId(用于区分不同小程序)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "formId", value = "formId(用于下发模板消息) ", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "ownerUnitPrice", value = "该路线运费单价(元/吨) ", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "reward", value = "奖励金", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "needModels", value = "所需车型", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "speedType", value = "次日达|隔日达|四日达|五日达", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String addDelivery(String openid, String startProvince, String startCity, String startDistrict, String startAddress, String endProvince, String endCity, String endDistrict,
                              String endAddress, String distance, String goodsName, String estimateWeight, String estimateVolume, String wholeCar
            , String loadTime, String remarks, String[] picPaths,
                              String startLng,
                              String startLat,
                              String endLng,
                              String endLat,
                              String ysxy,
                              int hwbx,
                              String hwbxText,
                              String leaveMsg,
                              String appId,
                              String loadTimeText,
                              String formId,
                              BigDecimal reward,
                              String ownerUnitPrice,//货主端的运输单价
                              String needModels,
                              String speedType
    ) {
        CommonJson result = new CommonJson();
        log.info("智慧物流发货申请 openid=" + openid + "|startProvince=" + startProvince + "|startCity=" + startCity
                + "|startAddress=" + startAddress + "|endProvince=" + endProvince
                + "|endAddress=" + endAddress + "|distance=" + distance + "|goodsName=" + goodsName
                + "|estimateWeight=" + estimateWeight + "|estimateVolume=" + estimateVolume
                + "|wholeCar=" + wholeCar + "|loadTime=" + loadTime + "|remarks=" + remarks
                + "|hwbxText=" + hwbxText + "|formId=" + formId + "|reward=" + reward
                +"|needModels="+needModels
                +"|speedType="+speedType   );
        if (StrUtil.isEmptyOrUndefined(appId)) {
            result.setMsg("appId不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (reward == null) {
            result.setMsg("reward不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisDelivery delivery = new LogisDelivery();
        delivery.setOpenid(openid);
        delivery.setDevOpenid(openid);
        delivery.setAppId(appId);
        delivery.setNeedModels(needModels);
        delivery.setSpeedType(speedType);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            delivery.setOpenid(user.getUnionId());//设置unionid
        }else{
            result.setMsg("未在开放平台绑定该小程序appid");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isNotBlank(ownerUnitPrice)) {
            delivery.setOwnerUnitPrice(new BigDecimal(ownerUnitPrice));
            delivery.setDriverUnitPrice(delivery.getOwnerUnitPrice().subtract(new BigDecimal("5")));
        }
        delivery.setStartProvince(startProvince);
        delivery.setStartCity(startCity);
        delivery.setStartAddress(startAddress);
        delivery.setEndProvince(endProvince);
        delivery.setEndCity(endCity);
        delivery.setEndAddress(endAddress);
        delivery.setDistance(distance);
        delivery.setGoodsName(goodsName);
        delivery.setEstimateWeight(estimateWeight);
        delivery.setEstimateVolume(estimateVolume);
        delivery.setWholeCar(wholeCar);
        delivery.setLoadTime(loadTime);
        delivery.setLoadTimeText(loadTimeText);
        delivery.setStatus("11");//已叫车,等待支付订金
        delivery.setPayStatus("0");
        delivery.setRemarks(remarks);
        delivery.setStartDistrict(startDistrict);
        delivery.setEndDistrict(endDistrict);
        delivery.setAuditStatus("0");
        delivery.setStartLat(startLat);
        delivery.setStartLng(startLng);
        delivery.setEndLat(endLat);
        delivery.setEndLng(endLng);
        delivery.setYsxy(ysxy);
        delivery.setHwbx(hwbx);
        delivery.setHwbxText(hwbxText);
        delivery.setLeaveMsg(leaveMsg);
        delivery.setDeposit(new BigDecimal("150"));//订金
        delivery.setInsuranceStatus(0);
        delivery.setFormId(formId);
        delivery.setReward(reward);
        logisDeliveryService.addDelivery(delivery, picPaths, openid);

        String page = "pages/gcDdXq/gcDdXq?deliveryId=" + delivery.getId();
        String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
        String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
        String keyword3 = delivery.getId();
        String keyword4 = "已叫车,订单未支付";
        String keyword5 = delivery.getCarrierStatusText();
        String keyword6 = "司机接单后更新";
        if (StrUtil.isNotBlank(delivery.getCarrierMobile())) {
            keyword6 = delivery.getCarrierMobile();
        }
        String keyword7 = "请尽快支付定金或转发给货主支付定金以确认订单。超时未支付订单将自动取消【百灵智慧物流】下单就有现金奖励，点击查看物流详情，祝您生意兴隆";
        wxService.sendTemplateMsg(appId, openid, page, formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);
        result.setData(delivery);
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "修改发货")
    @RequestMapping(value = "updateDelivery", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startProvince", value = "发货省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startCity", value = "发货城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startDistrict", value = "发货区", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startAddress", value = "发货详细地址", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endProvince", value = "目的地省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endCity", value = "目的地城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endDistrict", value = "目的地区", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endAddress", value = "收货详细地址", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "distance", value = "距离", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "goodsName", value = "货物名称", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "goodsWeight", value = "货物重量(真实)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "goodsVolume", value = "货物体积(真实)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "estimateWeight", value = "货物重量(预估)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "estimateVolume", value = "货物体积(预估)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "remarks", value = "备注", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startLng", value = "开始经度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startLat", value = "开始纬度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endLng", value = "目的地经度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endLat", value = "目的地纬度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "ysxy", value = "运输协议", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "insuranceFee0", value = "保险费(优惠前)", dataType = "BigDecimal", paramType = "form", required = true),
            @ApiImplicitParam(name = "insuranceFee", value = "保险费(优惠后)", dataType = "BigDecimal", paramType = "form", required = true),
            @ApiImplicitParam(name = "hwbx", value = "货物保险额(保险金额)", dataType = "int", paramType = "form", required = true),
            @ApiImplicitParam(name = "hwbxText", value = "货物保险额(文字描述)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "leaveMsg", value = "给司机留言", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "appId", value = "appId(用于区分不同小程序)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "picPaths", value = "图片数组", dataType = "String[]", paramType = "form"),
            @ApiImplicitParam(name = "openid", value = "String", dataType = "String[]", paramType = "form"
            ),
            @ApiImplicitParam(name = "hwbxYhText", value = "货物保险优惠(文字描述)", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "ownerUnitPrice", value = "该路线运费单价(元/吨) ", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "reward", value = "奖励金", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "speedType", value = "次日达|隔日达|四日达|五日达", dataType = "String", paramType = "form", required = true)

    })
    @ResponseBody
    public String updateDelivery(String id,
                                 String startProvince, String startCity, String startDistrict, String startAddress,
                                 String endProvince, String endCity, String endDistrict, String endAddress,
                                 String distance, String goodsName,
                                 String goodsWeight, String goodsVolume,
                                 String estimateWeight, String estimateVolume,
                                 String remarks,
                                 String startLng,
                                 String startLat,
                                 String endLng,
                                 String endLat,
                                 String ysxy,
                                 int hwbx,
                                 String hwbxText,
                                 String leaveMsg,
                                 String appId,
                                 String[] picPaths,
                                 BigDecimal insuranceFee0,
                                 BigDecimal insuranceFee,
                                 String hwbxYhText,
                                 String openid,
                                 BigDecimal reward,
                                 String ownerUnitPrice,
                                 String speedType) {
        CommonJson result = new CommonJson();
        log.info("修改发货申请 id=" + id + "|endAddress=" + endAddress + "|distance=" + distance + "|goodsName=" + goodsName + "|goodsWeight=" + goodsWeight + "|goodsVolume=" + goodsVolume
                + "|remarks=" + remarks + "insuranceFee=" + insuranceFee + "|openid" + openid + "|ownerUnitPrice=" + ownerUnitPrice
        );
        if (StrUtil.isEmptyOrUndefined(appId)) {
            result.setMsg("appId不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisDelivery delivery = logisDeliveryService.get(id);
//        if(delivery.getPayStatus()>=1){
//            result.setMsg("货主已支付订金，发货单信息不能再修改");
//            result.setCode(-1);
//            log.info("返回给小程序数据:" + this.mapper.toJson(result));
//            return this.mapper.toJson(result);
//        }

        if (StringUtils.isNotBlank(startProvince)) {
            delivery.setStartProvince(startProvince);
        }
        if (StringUtils.isNotBlank(startCity)) {
            delivery.setStartCity(startCity);
        }
        if (StringUtils.isNotBlank(startDistrict)) {
            delivery.setStartDistrict(startDistrict);
        }

        if (StringUtils.isNotBlank(startAddress)) {
            delivery.setStartAddress(startAddress);
        }
        if (StringUtils.isNotBlank(distance)) {
            delivery.setDistance(distance);
        }
        if (StringUtils.isNotBlank(endProvince)) {
            delivery.setEndProvince(endProvince);
        }
        if (StringUtils.isNotBlank(endCity)) {
            delivery.setEndCity(endCity);
        }
        if (StringUtils.isNotBlank(endDistrict)) {
            delivery.setEndDistrict(endDistrict);
        }

        if (StringUtils.isNotBlank(endAddress)) {
            delivery.setEndAddress(endAddress);
        }
        if (StringUtils.isNotBlank(distance)) {
            delivery.setDistance(distance);
        }
        if (StringUtils.isNotBlank(goodsName)) {
            delivery.setGoodsName(goodsName);
        }

        if (StringUtils.isNotBlank(estimateVolume)) {
            delivery.setEstimateVolume(estimateVolume);
        }
        if (StringUtils.isNotBlank(estimateWeight)) {
            delivery.setEstimateWeight(estimateWeight);
        }
        if (StringUtils.isNotBlank(remarks)) {
            delivery.setRemarks(remarks);
        }
        if (StringUtils.isNotBlank(startLat)) {
            delivery.setStartLat(startLat);
        }
        if (StringUtils.isNotBlank(startLng)) {
            delivery.setStartLng(startLng);
        }
        if (StringUtils.isNotBlank(endLat)) {
            delivery.setEndLat(endLat);
        }
        if (StringUtils.isNotBlank(endLng)) {
            delivery.setEndLng(endLng);
        }
        if (StringUtils.isNotBlank(ysxy)) {
            delivery.setYsxy(ysxy);
        }
        if (StringUtils.isNotBlank(hwbxYhText)) {
            delivery.setHwbxYhText(hwbxYhText);
        }
        if (StringUtils.isNotBlank(hwbxText) && !hwbxText.equals(delivery.getHwbxText())) {//跟之前的不相同
            delivery.setHwbx(hwbx);
            delivery.setHwbxText(hwbxText);//购买保险
            LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
            deliveryLog.setOpenid(openid);
            deliveryLog.setDeliveryId(delivery.getId());
            deliveryLog.setStatus("22");//货主选择保险
            logisDeliveryLogService.save(deliveryLog);

        }
        if (StringUtils.isNotBlank(leaveMsg)) {
            delivery.setLeaveMsg(leaveMsg);
        }
        if (insuranceFee != null) {
            delivery.setInsuranceFee(insuranceFee);//保险费
            if (delivery.getOwnerFreight() != null && delivery.getTax() != null) {
                delivery.setFreight(delivery.getOwnerFreight().add(delivery.getTax()).add(delivery.getInsuranceFee()));//重新计算总运费
            }
        }
        if (insuranceFee0 != null) {
            delivery.setInsuranceFee0(insuranceFee0);//保险费
        }
        if (!StrUtil.isBlankOrUndefined(ownerUnitPrice) && !"-1".equals(ownerUnitPrice)) {
            delivery.setOwnerUnitPrice(new BigDecimal(ownerUnitPrice));
            delivery.setDriverUnitPrice(delivery.getOwnerUnitPrice().subtract(new BigDecimal("5")));
        }

        if (reward != null) {
            delivery.setReward(reward);
        }
        if(StrUtil.isNotBlank(speedType)){
            delivery.setSpeedType(speedType);
        }
        logisDeliveryService.save(delivery);
        result.setData(delivery);
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 图片或视频上传
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "图片上传")
    @RequestMapping(value = "uploadPic", method = RequestMethod.POST)
    @ResponseBody
    public String uploadPic(MultipartFile file) throws Exception {
        CommonJson result = new CommonJson();
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/media/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;

        log.info("智慧物流 图片或视频上传到=" + path);
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            return mapper.toJson(result);
        }

        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            String filePath = "/userfiles/media/" + fileName + "." + extension;

            //String resizeFilePath = "/userfiles/media/" + fileName + "_resize." + extension;

            //ImageUtil.scale(new File(filePath), new File(resizeFilePath), 0.8f);

            String url = Global.getConfig("photoUrl") + filePath;
            UploadVO vo = new UploadVO();
            vo.setFilePath(filePath);
            vo.setUrl(url);
            result.setData(vo);
        }
        //  log.info("图片或视频上传返回:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 语音上传(返回语音文字)
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "语音上传(返回语音文字)")
    @RequestMapping(value = "uploadVoice", method = RequestMethod.POST)
    @ResponseBody
    public String uploadVoice(MultipartFile file) throws Exception {
        CommonJson result = new CommonJson();
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/voice/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;

        log.info("智慧物流 语音上传到=" + path);
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            return mapper.toJson(result);
        }

        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            String filePath = "userfiles/voice/" + fileName + "." + extension;
            String mp3filename = Global.getFileUploadPath() + filePath;
            String pcmfinename = Global.getFileUploadPath() + "userfiles/voice/" + fileName + ".pcm";
            log.info("mp3filename=" + mp3filename);
            log.info("pcmfinename=" + pcmfinename);
            try {
                MP3ConvertPCM.mp3Convertpcm(mp3filename, pcmfinename);
            } catch (Exception e) {
                log.info("mp3Convertpcm异常 =" + e.getMessage());
                e.printStackTrace();
            }
            log.info("语音文件 =" + pcmfinename);
            String data = AsrMain.voiceToWords(pcmfinename);
            log.info("识别出 =" + data);
            data = data.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\\\\", "").replaceAll("\"", "");
            log.info("去掉多余符号 =" + data);
            if ("该语音无法识别".equals(data)) {
                result.setCode(-1);
                result.setMsg("该语音无法识别");
            }
            result.setData(data);
        }
        //log.info("语音上传返回:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 我的发货
     */
    @ApiOperation(value = "我的发货单列表")
    @RequestMapping(value = "myDeliverys", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "0货主认领，-1货主确认1订单处理中2等待接单3司机已接单4准备装车5运输中6到达目的地7运费已付清8已卸车9运输已完成10订单已过期 11订单已取消",
                    dataType = "String", paramType = "query")
    })
    @ResponseBody
    public String myDeliverys(String openid, String status) {
        CommonJson result = new CommonJson();
        log.info("智慧物流 我的发货 openid=" + openid + "|status=" + status);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }

        LogisDelivery search = new LogisDelivery();
        if (StringUtils.isNotBlank(status)) {
            search.setStatus(status);
        }
        search.setOpenid(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setOpenid(user.getUnionId());
        }
        result.setData(logisDeliveryService.findList(search));
        // log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 我的历史货物名称
     */
    @ApiOperation(value = "历史货物名称")
    @RequestMapping(value = "historyGoodName", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String historyGoodName(String openid) {
        CommonJson result = new CommonJson();
        log.info("智慧物流 历史货物名称 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setOpenid(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setOpenid(user.getUnionId());
        }
        List<LogisDelivery> logisDeliveryList = logisDeliveryService.findList(search);
        Set<String> goosNameSet = new HashSet<String>();
        for (LogisDelivery delivery : logisDeliveryList) {
            goosNameSet.add(delivery.getGoodsName());
        }
        result.setData(goosNameSet);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 历史发货城市
     */
    @ApiOperation(value = "历史发货城市")
    @RequestMapping(value = "historyCity", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String historyCity(String openid) {
        CommonJson result = new CommonJson();
        log.info("智慧物流 历史城市名称 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setOpenid(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setOpenid(user.getUnionId());
        }
        List<LogisDelivery> logisDeliveryList = logisDeliveryService.findList(search);
        List<HistoryAddress> data = Lists.newArrayList();
        Map<String, String> ssqMap = new HashMap<String, String>();
        for (LogisDelivery delivery : logisDeliveryList) {
            String ssq = delivery.getEndProvince() + delivery.getEndCity();
            if (ssqMap.get(ssq) == null) {
                HistoryAddress historyAddress = new HistoryAddress();
                historyAddress.setProvince(delivery.getEndProvince());
                historyAddress.setCity(delivery.getEndCity());
                historyAddress.setDistrict(delivery.getEndDistrict());
                historyAddress.setAddress(delivery.getEndAddress());
                data.add(historyAddress);
                ssqMap.put(ssq, ssq);
            }
        }
        result.setData(data);
        // log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 历史路线
     */
    @ApiOperation(value = "历史发货路线")
    @RequestMapping(value = "historyDeliveryRoad", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String historyDeliveryRoad(String openid) {
        CommonJson result = new CommonJson();
        log.info("历史发货路线 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setOpenid(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setOpenid(user.getUnionId());
        }
        List<LogisDelivery> logisDeliveryList = logisDeliveryService.findList(search);
        List<DeliveryRoadVO> data = Lists.newArrayList();
        Map<String, String> ssqMap = new HashMap<String, String>();
        for (LogisDelivery delivery : logisDeliveryList) {
            String ssq = delivery.getStartProvince()+delivery.getStartCity()+delivery.getEndProvince() + delivery.getEndCity();
            if (ssqMap.get(ssq) == null) {
                DeliveryRoadVO historyAddress = new DeliveryRoadVO();
                historyAddress.setStartProvince(delivery.getStartProvince());
                historyAddress.setStartCity(delivery.getStartCity());
                historyAddress.setEndAddress(delivery.getEndAddress());
                historyAddress.setStartAddress(delivery.getStartAddress());
                historyAddress.setEndProvince(delivery.getEndProvince());
                historyAddress.setEndCity(delivery.getEndCity());
                historyAddress.setStartArea(delivery.getStartDistrict());
                historyAddress.setEndArea(delivery.getEndDistrict());
                historyAddress.setStartLat(delivery.getStartLat());
                historyAddress.setStartLng(delivery.getStartLng());
                data.add(historyAddress);
                ssqMap.put(ssq, ssq);
            }
        }
        result.setData(data);
        // log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 根据状态获取发货单
     */
    @ApiOperation(value = "根据状态获取发货单(客服已发布的)")
    @RequestMapping(value = "getDeliverysByStatus", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "status", value = "11已叫车,等待支付订金 12已付订金，正在调度司机 13司机接单,运输中,14已卸车,运输完成 15订单关闭,超时未付款 16调度失败,司机超时未接单,17订单取消,货运计划变更", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getDeliverysByStatus(String status) {
        CommonJson result = new CommonJson();
        log.info("根据状态获取发货申请 status=" + status);
        if (StrUtil.isEmptyOrUndefined(status)) {
            result.setMsg("status不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setStatus(status);
        search.setAuditStatus("1");//审核通过,已发布的
        List<LogisDelivery> deliveries = logisDeliveryService.findList(search);
        List<LogisDelivery> data = Lists.newArrayList();
        for (LogisDelivery delivery : deliveries) {
            data.add(logisDeliveryService.get(delivery.getId()));
        }
        result.setData(data);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    /**
     * 根据路线匹配发货单
     */
    @ApiOperation(value = "根据路线匹配发货单")
    @RequestMapping(value = "getDeliverysByRoad", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startCitys", value = "开始城市(多个|分割) ", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startArea", value = "开始区(多个|分割),没有的话传空串 ", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "endCitys", value = "目的城市(多个|分割) ", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endArea", value = "目的区(多个|分割),没有的话传空串 ", dataType = "String", paramType = "form"),
    })
    @ResponseBody
    public String getDeliverysByRoad(String startCitys, String endCitys,String startArea,String endArea) {
        CommonJson result = new CommonJson();
        log.info("根据路线匹配发货单 startCitys=" + startCitys + "|endCitys=" + endCitys+"|endArea="+endArea+"|startArea="+startArea);
        if (StrUtil.isEmptyOrUndefined(startCitys)) {
            result.setMsg("startCitys不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(endCitys)) {
            result.setMsg("endCitys不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setStatus("12");
        search.setAuditStatus("1");//审核通过,已发布的
        List<LogisDelivery> deliveries = logisDeliveryService.findList(search);
        List<LogisDelivery> matchs = Lists.newArrayList();
        List<LogisDelivery> others = Lists.newArrayList();
        for (LogisDelivery delivery : deliveries) {
            if (startCitys.contains(delivery.getStartCity()) && endCitys.contains(delivery.getEndCity())) {
                matchs.add(logisDeliveryService.get(delivery.getId()));
            }else{
                others.add(logisDeliveryService.get(delivery.getId()));
            }
        }
        RoadDeliveryVO data = new RoadDeliveryVO();
        data.setMatchs(matchs);
        data.setOthers(others);
        result.setData(data);
        result.setMsg(matchs.size() + "");
        // log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    /**
     * 我的运输单(司机)
     */
    @ApiOperation(value = "我的运输单列表(司机)")
    @RequestMapping(value = "myCarriers", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "11已叫车,等待支付订金 12已付订金，正在调度司机 13司机接单,运输中,14已卸车,运输完成 15订单关闭,超时未付款 16调度失败,司机超时未接单,17订单取消,货运计划变更",
                    dataType = "String", paramType = "query")
    })
    @ResponseBody
    public String myCarriers(String openid, String status) {
        CommonJson result = new CommonJson();
        log.info("我的运输单 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setCarrier(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setCarrier(user.getUnionId());
        }
        if (StringUtils.isNotBlank(status)) {
            search.setStatus(status);
        }
        result.setData(logisDeliveryService.findList(search));
        return this.mapper.toJson(result);
    }

    /**
     * 我的收货单
     */
    @ApiOperation(value = "我的收货单列表(货主)")
    @RequestMapping(value = "myReceives", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "//11已叫车,等待支付订金 12已付订金，正在调度司机 13司机接单,运输中,14已卸车,运输完成 15订单关闭,超时未付款 16调度失败,司机超时未接单,17订单取消,货运计划变更",
                    dataType = "String", paramType = "query")
    })
    @ResponseBody
    public String myReceives(String openid, String status) {
        CommonJson result = new CommonJson();
        log.info("我的收货单 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setReceiver(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setReceiver(user.getUnionId());
        }

        if (StringUtils.isNotBlank(status)) {
            search.setStatus(status);
        }
        result.setData(logisDeliveryService.findList(search));
        return this.mapper.toJson(result);
    }

    /**
     * 发货单详情
     */
    @ApiOperation(value = "发货单详情")
    @RequestMapping(value = "deliveryInfo", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "deliveryId", value = "编号", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String deliveryInfo(String deliveryId) {
        CommonJson result = new CommonJson();
        log.info("发货单详情 deliveryId=" + deliveryId);
        if (StrUtil.isEmptyOrUndefined(deliveryId)) {
            result.setMsg("deliveryId不能为空");
            result.setCode(1);
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisDelivery delivery = logisDeliveryService.get(deliveryId);
        result.setData(delivery);
        return this.mapper.toJson(result);
    }

    /**
     * 获取两点驾车距离
     */
    @ApiOperation(value = "获取两点驾车距离")
    @RequestMapping(value = "getDrivingDistance", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "startAddress", value = "开始地址", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endAddress", value = "目的地地址", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String getDrivingDistance(String startAddress, String endAddress) {
        CommonJson result = new CommonJson();
        log.info("获取亮点驾车距离 startAddress=" + startAddress + "|endAddress=" + endAddress);
        if (StrUtil.isEmptyOrUndefined(startAddress)) {
            result.setMsg("startAddress不能为空");
            result.setCode(1);
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(endAddress)) {
            result.setMsg("endAddress不能为空");
            result.setCode(1);
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        Map<String, Double> startMap = BaiduAPI.getLngAndLat(startAddress);
        Map<String, Double> endMap = BaiduAPI.getLngAndLat(endAddress);
        Map<String, String> distanceMap = BaiduAPI.getDistanceByPoints(startMap, endMap);
        result.setData(distanceMap);
        return this.mapper.toJson(result);
    }

    /**
     * 获取两点建议报价
     */
    @ApiOperation(value = "获取两地指导报价")
    @RequestMapping(value = "getDistancePrice", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "startAddress", value = "开始地址", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endAddress", value = "目的地地址", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String getDistancePrice(String startAddress, String endAddress) {
        CommonJson result = new CommonJson();
        log.info("获取两地指导报价 startAddress=" + startAddress + "|endAddress=" + endAddress);
        if (StrUtil.isEmptyOrUndefined(startAddress)) {
            result.setMsg("startAddress不能为空");
            result.setCode(1);
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(endAddress)) {
            result.setMsg("endAddress不能为空");
            result.setCode(1);
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        Map<String, Double> startMap = BaiduAPI.getLngAndLat(startAddress);
        Map<String, Double> endMap = BaiduAPI.getLngAndLat(endAddress);
        String distanceStr = BaiduAPI.getDistance(startMap, endMap);
        if ("0".equals(distanceStr)) {
            distanceStr = BaiduAPI.getDistance(startMap, endMap);
        }
        int distance = Integer.parseInt(distanceStr);
        int price = (distance / 10000) * 2;
        if (price < 100) {
            price = price + 20;
        }
        result.setData(price);
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "获取我的积分列表")
    @RequestMapping(value = "getScoreList", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String getScoreList(String openid) {
        log.info("获取我的积分列表 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        GasScore search = new GasScore();
        LogisUser user = logisUserService.get(openid);
        if (StrUtil.isNotBlank(user.getUnionId())) {
            search.setUnionId(user.getUnionId());
        } else {
            search.setOpenid(openid);
        }
        List<GasScore> scores = this.gasScoreService.findList(search);
        result.setData(scores);
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "获取我的奖励金列表")
    @RequestMapping(value = "getRewardList", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String getRewardList(String openid) {
        log.info("获取我的奖励金列表 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        GasRecharge search = new GasRecharge();
        LogisUser user = logisUserService.get(openid);
        if (StrUtil.isNotBlank(user.getUnionId())) {
            search.setUnionId(user.getUnionId());
        } else {
            search.setOpenid(openid);
        }
        List<GasRecharge> rewards = this.gasRechargeService.findList(search);
        result.setData(rewards);
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "获取动态变量")
    @RequestMapping(value = "getDynamicInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getDynamicInfo() {
        log.info("获取动态变量");
        CommonJson result = new CommonJson();
        ScoreVO scoreVO = new ScoreVO();
        scoreVO.setOrderSucessReward(Integer.parseInt(ConfigUtils.getProperty("orderSucessReward")));
        scoreVO.setOrderSucessScore(Integer.parseInt(ConfigUtils.getProperty("orderSucessScore")));
        scoreVO.setShareFriendRegScore(Integer.parseInt(ConfigUtils.getProperty("shareFriendRegScore")));
        scoreVO.setActiveText(ConfigUtils.getProperty("activeText"));
        result.setData(scoreVO);
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "常用路线")
    @RequestMapping(value = "commonRoads", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String commonRoads(String openid) {
        log.info("常用路线 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery search = new LogisDelivery();
        search.setOpenid(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setOpenid(user.getUnionId());
        }
        List<LogisDelivery> logisDeliveries = this.logisDeliveryService.findList(search);
        List<RoadVO> roadVOList = Lists.newArrayList();
        for (LogisDelivery delivery : logisDeliveries) {
            if (StringUtils.isNotBlank(delivery.getStartCity()) && StringUtils.isNotBlank(delivery.getStartDistrict()) &&
                    StringUtils.isNotBlank(delivery.getEndCity()) && StringUtils.isNotBlank(delivery.getEndDistrict())) {
                RoadVO roadVO = new RoadVO();
                roadVO.setStartCity(delivery.getStartCity());
                roadVO.setStartDistrict(delivery.getStartDistrict());
                roadVO.setEndCity(delivery.getEndCity());
                roadVO.setEndDistrict(delivery.getEndDistrict());
                roadVOList.add(roadVO);
            }
        }
        result.setData(roadVOList);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "我的好友列表")
    @RequestMapping(value = "myFriends", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String myFriends(String openid) {
        log.info("我的好友 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisShareFriend search = new LogisShareFriend();
        LogisUser user = logisUserService.get(openid);
        search.setFriendOpenid(openid);
//        if (AppIdType.PARTNER.equals(user.getAppId())) {
//            search.setType(1);//车队
//        } else {
//            search.setType(0);//好友
//        }
        List<LogisShareFriend> logisShareFriends = this.logisShareFriendService.findList(search);
        user.setFriendNum(logisShareFriends.size());
        logisUserService.save(user);//更新下用户好友
        List<LogisUser> userList = Lists.newArrayList();
        for (LogisShareFriend friend : logisShareFriends) {

            LogisDelivery deliverySearch = new LogisDelivery();
            deliverySearch.setOpenid(friend.getOpenid());
            user = logisUserService.get(friend.getOpenid());
            if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
                deliverySearch.setOpenid(user.getUnionId());
            }

            int jiaocheNum = 0;
            int chengjiaoNum = 0;
            List<LogisDelivery> todayLists = logisDeliveryService.findList(deliverySearch);
            for (LogisDelivery delivery : todayLists) {
                jiaocheNum++;
                if (!"16".equals(delivery.getStatus()) && !"17".equals(delivery.getStatus()) && !"18".equals(delivery.getStatus())) {
                    //jiaocheNum++;
                }
                if ("15".equals(delivery.getStatus())) {
                    chengjiaoNum++;
                }
            }
            user.setJiaocheNum(jiaocheNum);
            user.setChengjiaoNum(chengjiaoNum);


            GasRecharge gasSearch = new GasRecharge();
            gasSearch.setOpenid(openid);
            gasSearch.setSupportOpenid(friend.getOpenid());
            List<GasRecharge> gasRecharges = gasRechargeService.findList(gasSearch);
            BigDecimal gainReward = new BigDecimal("0");
            for(GasRecharge gasRecharge:gasRecharges){
                gainReward = gainReward.add(gasRecharge.getAmount());
            }
            user.setGainReward(gainReward);
            userList.add(user);
        }
        Collections.sort(userList, new Comparator<LogisUser>(){
            public int compare(LogisUser o1, LogisUser o2) {
                if(o1.getGainReward().intValue() < o2.getGainReward().intValue()){
                    return 1;
                }
                if(o1.getGainReward().intValue() == o2.getGainReward().intValue()){
                    return 0;
                }
                return -1;
            }
        });
        result.setData(userList);
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "今日好友下单")
    @RequestMapping(value = "todayFriendOrder", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String todayFriendOrder(String openid) {
        log.info("今日好友下单 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisShareFriend search = new LogisShareFriend();
        search.setFriendOpenid(openid);
        List<LogisShareFriend> logisShareFriends = this.logisShareFriendService.findList(search);
        List<LogisUser> userList = Lists.newArrayList();
        int todayJioacheNum = 0;
        for (LogisShareFriend friend : logisShareFriends) {
            LogisDelivery deliverySearch = new LogisDelivery();
            deliverySearch.setOpenid(friend.getOpenid());
            LogisUser user = logisUserService.get(friend.getOpenid());
            if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
                deliverySearch.setOpenid(user.getUnionId());
            }
            deliverySearch.setStartDate(DateUtil.beginOfDay(DateUtil.date()));
            deliverySearch.setEndDate(DateUtil.endOfDay(DateUtil.date()));
            int jiaocheNum = 0;
            int chengjiaoNum = 0;
            List<LogisDelivery> todayLists = logisDeliveryService.findList(deliverySearch);
            for (LogisDelivery delivery : todayLists) {
                jiaocheNum++;
                if (!"16".equals(delivery.getStatus()) && !"17".equals(delivery.getStatus()) && !"18".equals(delivery.getStatus())) {
                    //jiaocheNum++;
                }
                if ("15".equals(delivery.getStatus())) {
                    chengjiaoNum++;
                }
            }

            if (jiaocheNum > 0) {
                user = logisUserService.get(friend.getOpenid());
                user.setJiaocheNum(jiaocheNum);
                user.setChengjiaoNum(chengjiaoNum);
                userList.add(user);
            }
            todayJioacheNum = todayJioacheNum + jiaocheNum;
        }
        Collections.sort(userList, new Comparator<LogisUser>(){
            public int compare(LogisUser o1, LogisUser o2) {
                if(o1.getChengjiaoNum() < o2.getChengjiaoNum()){
                    return 1;
                }
                if(o1.getChengjiaoNum() == o2.getChengjiaoNum()){
                    return 0;
                }
                return -1;
            }
        });
        result.setMsg(todayJioacheNum + "");
        result.setData(userList);
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "今日奖励金")
    @RequestMapping(value = "todayReward", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String todayReward(String openid) {
        log.info("今日奖励金 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        GasRecharge search = new GasRecharge();
        LogisUser user = logisUserService.get(openid);
        search.setUnionId(user.getUnionId());
        search.setStartDate(DateUtil.beginOfDay(DateUtil.date()));
        search.setEndDate(DateUtil.endOfDay(DateUtil.date()));
        search.setComeFrom("1");
        List<GasRecharge> recharges = this.gasRechargeService.findList(search);
        int totalReward = 0;
        for (GasRecharge recharge : recharges) {
            totalReward += recharge.getAmount().intValue();

        }
        result.setData(totalReward);
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "推广奖励金(累积)")
    @RequestMapping(value = "totalReward", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String totalReward(String openid) {
        log.info("累积奖励金 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        GasRecharge search = new GasRecharge();
        LogisUser user = logisUserService.get(openid);
        search.setUnionId(user.getUnionId());
        search.setComeFrom("1");
        List<GasRecharge> recharges = this.gasRechargeService.findList(search);
        int totalReward = 0;
        for (GasRecharge recharge : recharges) {
            totalReward += recharge.getAmount().intValue();

        }
        result.setData(totalReward);
        return this.mapper.toJson(result);
    }

    @Autowired
    private WxMyPayService wxPayService;

    /**
     * 返回前台H5调用JS支付所需要的参数，公众号支付调用此接口
     *
     * @param deliveryId 订单id
     * @param request
     * @return
     */
    @ApiOperation(value = "微信支付所需参数")
    @RequestMapping(value = "getJSSDKPayInfo", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "deliveryId", value = "运单id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "appId", value = "appId", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "type", value = "1支付订金，2支付尾款", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String getJSSDKPayInfo(String openid, String deliveryId, HttpServletRequest request, String appId, String type) {
        log.info("getJSSDKPayInfo 拉起微信支付 deliveryId=" + deliveryId + "|openid=" + openid + "|appId=" + appId + "type=" + type);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(appId)) {
            result.setMsg("appId不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(deliveryId)) {
            result.setMsg("deliveryId不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(type)) {
            result.setMsg("type不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        WxMpAccount wxMpAccount = wxMpAccountService.get(appId);
        String macid = wxMpAccount.getMchId();
        String key = wxMpAccount.getMchKey();
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        String notifyUrl = basePath + Global.getFrontPath() + "/wxPayback/notify/" + type + "/" + deliveryId;
        LogisDelivery order = this.logisDeliveryService.get(deliveryId);
        if (order == null) {
            result.setCode(-1);
            result.setMsg("订单不存在");
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }

        String body = "支付运费订金" + order.getDeposit() + "元";
        BigDecimal totalMoney = order.getTotalDeposit();//order.getDeposit();
        if ("1".equals(type)) {//支付订金
            if (order.getDeposit() == null) {
                result.setCode(-1);
                result.setMsg("请先设置订金");
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
            if ("1".equals(order.getPayStatus())) {
                result.setCode(-1);
                result.setMsg("订金已支付，无需重复支付");
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
            if (StrUtil.isNotBlank(order.getWxOrderId())) {
                result.setMsg("订金已支付，无需重复支付");
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
        }
        if ("2".equals(type)) {
            if (StrUtil.isBlank(order.getGoodsWeight())) {
                result.setCode(-1);
                result.setMsg("货物真实重量未设置,无法支付");
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
            if (order.getDriverUnitPrice() == null) {
                result.setCode(-1);
                result.setMsg("请先设置运费单价(司机端)");
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
            if (order.getOwnerUnitPrice() == null) {
                result.setCode(-1);
                result.setMsg("请先设置运费单价(货主端)");
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
            if ("2".equals(order.getPayStatus())) {
                result.setCode(-1);
                result.setMsg("尾款已支付，无需重复支付");
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
            body = "支付运费尾款" + order.getRetainage() + "元";
            totalMoney = order.getRetainage();
        }
        String json = this.wxPayService.getPayInfo(deliveryId, body, totalMoney, appId, macid, openid, request, key, notifyUrl, type);
        result.setData(json);
        return this.mapper.toJson(result);
    }

    public static Logger payLog = LoggerFactory.getLogger("payLog");

    @ApiOperation(value = "微信支付日志回调(最终支付状态以微信支付回调接口为主)")
    @RequestMapping(value = "wxPayOk", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "deliveryId", value = "运单id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "type", value = "1支付订金，2支付尾款", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "支付者openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "shareOpenid", value = "分享者openid", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "formId", value = "formId", dataType = "String", paramType = "form", required = true),
    })
    @ResponseBody
    public String wxPayOk(String deliveryId, String type, String openid, String shareOpenid, String formId) {
        payLog.info("支付成功调用wxPayOk orderId=" + deliveryId + "type=" + type + "|openid=" + openid + "|formId=" + formId+"|shareOpenid="+shareOpenid);
        CommonJson result = new CommonJson();
        LogisDelivery delivery = this.logisDeliveryService.get(deliveryId);
        if (delivery == null) {
            result.setCode(-1);
            result.setMsg("订单不存在");
            payLog.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(type)) {
            result.setMsg("type不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }

        if ("1".equals(type)) {//支付预付金
            payLog.info("支付的是订金");
            LogisUser logisUser = logisUserService.get(openid);
            if(logisUser!=null){
                logisUser.setShouhuoNum(logisUser.getShouhuoNum() + 1);
                logisUserService.save(logisUser);
            }
            delivery.setReceiver(logisUser.getUnionId());
            delivery.setRecOpenid(openid);//设置收货人
            if (StrUtil.isNotBlank(shareOpenid)) {
                LogisUser shareUser = logisUserService.get(shareOpenid);
                if(shareUser!=null){
                    shareUser.setShouhuoNum(shareUser.getShouhuoNum() + 1);
                    logisUserService.save(shareUser);
                }
                delivery.setReceiver(logisUser.getUnionId() + "|" + shareUser.getUnionId());
            }
            delivery.setPayStatus("1");
            delivery.setInsuranceStatus(1);
            delivery.setStatus("12");//已付订金，正在调度司机
            delivery.setReceiverStatus("23");//已付定金，对接运输问题
            logisDeliveryService.save(delivery);


            LogisInsurePhoto insurePhoto = logisInsurePhotoService.get(deliveryId);
            if (insurePhoto == null) {
                insurePhoto = new LogisInsurePhoto();
                insurePhoto.setId(deliveryId);
                insurePhoto.setStatus1("0");
                insurePhoto.setStatus2("0");
                insurePhoto.setStatus3("0");
                insurePhoto.setStatus4("0");
                insurePhoto.setStatus5("0");
            }
            insurePhoto.setGoodsName(delivery.getGoodsName());
            insurePhoto.setStartAddress(delivery.getStartProvince() + delivery.getStartCity());
            insurePhoto.setEndAddress(delivery.getEndProvince() + delivery.getEndCity());
            insurePhoto.setDriverName(delivery.getCarrierName());
            insurePhoto.setLicensePlate(delivery.getLicensePlate());
            insurePhoto.setReceiverName(delivery.getReceiverName());
            insurePhoto.setReceiverMobile(delivery.getReceiverMobile());
            insurePhoto.setDeliveryId(deliveryId);
            insurePhoto.setHwbx(delivery.getHwbx());
            insurePhoto.setHwbxText(delivery.getHwbxText());
            insurePhoto.setPolicyDate(DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
            insurePhoto.setPolicyStartDate(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 1), "yyyy-MM-dd"));
            insurePhoto.setPolicyEndDate(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 9), "yyyy-MM-dd"));
            logisInsurePhotoService.save(insurePhoto);


            payLog.info("wxPayOk,支付订金成功，货主认领货物 deliveryId=" + delivery.getId() + "| openid=" + openid + "|unionId=" + delivery.getReceiver());
            LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
            deliveryLog.setOpenid(openid);
            deliveryLog.setDeliveryId(deliveryId);
            deliveryLog.setStatus("23");//已付定金，对接运输问题
            deliveryLog.setType("2");
            logisDeliveryLogService.save(deliveryLog);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            deliveryLog = new LogisDeliveryLog();
            deliveryLog.setOpenid(openid);
            deliveryLog.setDeliveryId(delivery.getId());
            deliveryLog.setStatus("12");//12已付订金，正在调度司机
            deliveryLog.setType("2");
            logisDeliveryLogService.save(deliveryLog);


            //发给收货人
            String page = "/pages/hzDd/hzDd?deliveryId=" + delivery.getId() + "&shareOpenid=&shareState=0";
            String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
            String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
            String keyword3 = delivery.getId();
            String keyword4 = "已付订金，正在调度司机";
            String keyword5 = delivery.getCarrierStatusText();
            String keyword6 = "司机接单后更新";
            if (StrUtil.isNotBlank(delivery.getCarrierMobile())) {
                keyword6 = delivery.getCarrierMobile();
            }
            try {
                String keyword7 = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
                wxService.sendTemplateMsg(delivery.getAppId(), delivery.getRecOpenid(), page,
                        formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);

                //发给发货人
                page = "pages/gcDdXq/gcDdXq?deliveryId=" + delivery.getId();
                wxService.sendTemplateMsg(delivery.getAppId(), delivery.getDevOpenid(), page,
                        formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {//支付尾款，运费已付清
            delivery.setPayStatus("2");
            delivery.setReceiverStatus("24");//已付定金，对接运输问题
            logisDeliveryService.save(delivery);

            LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
            deliveryLog.setOpenid(openid);
            deliveryLog.setDeliveryId(deliveryId);
            deliveryLog.setType("2");
            deliveryLog.setStatus("24");//货主已支付运费尾款
            logisDeliveryLogService.save(deliveryLog);

            //发给收货人
            String page = "/pages/hzDd/hzDd?deliveryId=" + delivery.getId() + "&shareOpenid=&shareState=0";
            String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
            String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
            String keyword3 = delivery.getId();
            String keyword4 = "已支付运费尾款";
            String keyword5 = delivery.getCarrierStatusText();
            String keyword6 = "司机接单后更新";
            if (StrUtil.isNotBlank(delivery.getCarrierMobile())) {
                keyword6 = delivery.getCarrierMobile();
            }
            String keyword7 = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
            try {
                wxService.sendTemplateMsg(delivery.getAppId(), delivery.getRecOpenid(), page,
                        formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);

                //发给发货人
                page = "pages/gcDdXq/gcDdXq?deliveryId=" + delivery.getId();
                wxService.sendTemplateMsg(delivery.getAppId(), delivery.getDevOpenid(), page,
                        formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        result.setData(delivery);
        payLog.info("调用wxPayOk 成功！");
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "司机设置车辆信息")
    @RequestMapping(value = "setCar", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "licensePlate", value = "车牌", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "idcardImg1", value = "身份证相片正面(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "idcardImg2", value = "身份证相片反面(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "jszImg1", value = "驾驶证照片(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "xszImg1", value = "行驶证照片(副本)(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "jszImg2", value = "驾驶证照片（副本）(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "xszImg2", value = "行驶证照片(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "carHeadImg", value = "车头照片(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "driverType", value = "司机类型(1主驾驶 2副驾驶)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "remarks", value = "车辆信息", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "idCardNo", value = "身份证号", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "realName", value = "真实姓名", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "birthDay", value = "生日", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "address", value = "住址", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "gender", value = "性别", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "models", value = "车型", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "trailerLicensePlate", value = "挂车车牌", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "gcXszImg1", value = "挂车行驶证", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "gcXszImg2", value = "挂车行驶证副本", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "carLength", value = "车长", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "loadweight", value = "和载重量", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "headImg", value = "司机头像", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String setCar(String driverType, String openid, String licensePlate, String jszImg1, String xszImg1,
                         String idcardImg1, String idcardImg2, String carHeadImg, String remarks,
                         String idCardNo,
                         String realName,
                         String birthDay,
                         String address,
                         String gender,
                         String models,
                         String trailerLicensePlate,
                         String jszImg2,
                         String xszImg2,
                         String gcXszImg1,
                         String gcXszImg2,
                         String carLength,
                         String loadweight,
                         String headImg

    ) {
        log.info("司机设置车辆信息 openid=" + openid + "|licensePlate=" + licensePlate + "|jszImg1=" + jszImg1 + "|xszImg1=" + xszImg1);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisCar logisCar = new LogisCar();
        logisCar.setId(openid);
        if (StringUtils.isNotBlank(licensePlate)) {
            logisCar.setLicensePlate(licensePlate);
        }
        if (StringUtils.isNotBlank(trailerLicensePlate)) {
            logisCar.setTrailerLicensePlate(trailerLicensePlate);
        }


        if (StringUtils.isNotBlank(carLength)) {
            logisCar.setCarLength(carLength);
        }
        if (StringUtils.isNotBlank(loadweight)) {
            logisCar.setLoadweight(loadweight);
        }
        if (StringUtils.isNotBlank(jszImg2)) {
            logisCar.setJszImg2(jszImg2);
        }
        if (StringUtils.isNotBlank(xszImg2)) {
            logisCar.setXszImg2(xszImg2);
        }
        if (StrUtil.isNotBlank(idcardImg2)) {
            logisCar.setIdcardImg2(idcardImg2);
        }
        if (StrUtil.isNotBlank(jszImg1)) {
            logisCar.setJszImg1(jszImg1);
        }
        if (StrUtil.isNotBlank(jszImg2)) {
            logisCar.setJszImg2(jszImg2);
        }
        if (StrUtil.isNotBlank(xszImg1)) {
            logisCar.setXszImg1(xszImg1);
        }

        if (StringUtils.isNotBlank(models)) {
            logisCar.setModels(models);
        }

        if (StringUtils.isNotBlank(idcardImg1)) {
            logisCar.setIdcardImg1(idcardImg1);
        }
        if (StringUtils.isNotBlank(idcardImg2)) {
            logisCar.setIdcardImg2(idcardImg2);
        }
        if (StringUtils.isNotBlank(carHeadImg)) {
            logisCar.setCarHeadImg(carHeadImg);
        }
        if (StrUtil.isNotBlank(gcXszImg1)) {
            logisCar.setGcXszImg1(gcXszImg1);
        }
        if (StrUtil.isNotBlank(gcXszImg2)) {
            logisCar.setGcXszImg2(gcXszImg2);
        }
        if (StringUtils.isNotBlank(remarks)) {
            logisCar.setRemarks(remarks);
        }
        if (StringUtils.isNotBlank(driverType)) {
            logisCar.setDriverType(driverType);
        }
        if (StringUtils.isNotBlank(headImg)) {
            logisCar.setHeadImg(headImg);
        }
        logisCar.setCarStatus(0);
        logisCar.setDriverStatus(0);
        LogisCar old = logisCarService.get(openid);
        if (old != null && old.getCarStatus() == 1) {
            logisCar.setCarStatus(1);
        }
        if (old != null && old.getDriverStatus() == 1) {
            logisCar.setDriverStatus(1);
        }

        if(StrUtil.isNotBlank(realName)){
            logisCar.setRealName(realName);
        }
        if(StrUtil.isNotBlank(idCardNo)){
            logisCar.setIdCardNum(idCardNo);
        }

        if(StrUtil.isNotBlank(address)){
            logisCar.setAddress(address);
        }
        if(StrUtil.isNotBlank(gender)){
            logisCar.setGender(gender);
        }
        if(StrUtil.isNotBlank(birthDay)) {
            logisCar.setBirthDay(birthDay);
        }
        logisCarService.save(logisCar);
        if (StrUtil.isNotBlank(logisCar.getRealName())) {
            LogisUser user = logisUserService.get(logisCar.getId());
            user.setRealName(logisCar.getRealName());
            logisUserService.save(user);
        }
        result.setData(logisCar);
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "车辆认证信息")
    @RequestMapping(value = "myCarInfo", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String myCarInfo(String openid) {
        log.info("我的车辆认证信息 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisCar logisCar = logisCarService.get(openid);
        result.setData(logisCar);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


//    @ApiOperation(value = "司机与车辆认证")
//    @RequestMapping(value = "authCarAndDriver", method = RequestMethod.POST)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "headImg", value = "头像(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "jszImg1", value = "驾驶证照片(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "idcardImg1", value = "身份证相片正面(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "driverType", value = "司机类型(1主驾驶 2副驾驶)", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "licensePlate", value = "车牌", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "models", value = "车型", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "carLength", value = "车长", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "loadweight", value = "和载重量", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "xszImg1", value = "行驶证正本(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
//            @ApiImplicitParam(name = "xszImg2", value = "行驶证副本(调用上传接口后的路径)", dataType = "String", paramType = "form", required = true),
//
//    })
//    @ResponseBody
//    public String authCarAndDriver(String openid, String headImg, String jszImg1, String idcardImg1, String driverType,
//                                   String loadweight, String licensePlate, String models, String carLength, String xszImg1, String xszImg2) {
//        log.info("司机与车辆认证 openid=" + openid + "|licensePlate=" + licensePlate + "|jszImg1=" + jszImg1 + "|xszImg1=" + xszImg1 + "|headImg=" + headImg);
//        CommonJson result = new CommonJson();
//        if (StrUtil.isEmptyOrUndefined(openid)) {
//            result.setMsg("openid不能为空");
//            result.setCode(1);
//            return this.mapper.toJson(result);
//        }
//        LogisCar logisCar = logisCarService.get(openid);
//        if (logisCar == null) {
//            logisCar = new LogisCar();
//            logisCar.setCarStatus(0);
//            logisCar.setDriverStatus(0);
//        }
//        logisCar.setId(openid);
//
//        if (StrUtil.isBlank(headImg) && StrUtil.isBlank(logisCar.getHeadImg())) {
//            result.setMsg("headImg不能为空");
//            result.setCode(1);
//            return this.mapper.toJson(result);
//        }
//        if (StrUtil.isBlank(jszImg1) && StrUtil.isBlank(logisCar.getJszImg1())) {
//            result.setMsg("jszImg1不能为空");
//            result.setCode(1);
//            return this.mapper.toJson(result);
//        }
//        if (StrUtil.isBlank(idcardImg1) && StrUtil.isBlank(logisCar.getIdcardImg1())) {
//            result.setMsg("idcardImg1不能为空");
//            result.setCode(1);
//            return this.mapper.toJson(result);
//        }
//
//        if (StrUtil.isNotBlank(headImg)) {
//            logisCar.setHeadImg(headImg);
//        }
//        if (StringUtils.isNotBlank(jszImg1)) {
//            logisCar.setJszImg1(jszImg1);
//        }
//        if (StringUtils.isNotBlank(idcardImg1)) {
//            logisCar.setIdcardImg1(idcardImg1);
//        }
//        if (StringUtils.isNotBlank(driverType)) {
//            logisCar.setDriverType(driverType);
//        }
//        if (StringUtils.isNotBlank(models)) {
//            logisCar.setModels(models);
//        }
//
//        if (StringUtils.isNotBlank(licensePlate)) {
//            logisCar.setLicensePlate(licensePlate);
//        }
//        if (StringUtils.isNotBlank(carLength)) {
//            logisCar.setCarLength(carLength);
//        }
//        if (StringUtils.isNotBlank(xszImg1)) {
//            logisCar.setXszImg1(xszImg1);
//        }
//        if (StringUtils.isNotBlank(xszImg2)) {
//            logisCar.setXszImg2(xszImg2);
//        }
//        if (StringUtils.isNotBlank(loadweight)) {
//            logisCar.setLoadweight(loadweight);
//        }
//        if (logisCar.getCarStatus() == 2) {
//            logisCar.setCarStatus(0);
//        }
//        if (logisCar.getDriverStatus() == 2) {
//            logisCar.setDriverStatus(0);
//        }
//
//        logisCarService.save(logisCar);
//        result.setData(logisCar);
//        //log.info("返回微信小程序" + mapper.toJson(result));
//        return this.mapper.toJson(result);
//    }


    @ApiOperation(value = "车辆司机认证信息")
    @RequestMapping(value = "carAndDriverAuthInfo", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String carAndDriverAuthInfo(String openid) {
        log.info("车辆司机认证信息 openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisCar logisCar = logisCarService.get(openid);
        result.setData(logisCar);
        log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @Autowired
    private LogisCarRoadService logisCarRoadService;


    @ApiOperation(value = "司机设置路线信息")
    @RequestMapping(value = "setCarRoad", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startProvince", value = "出发省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startCity", value = "出发城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startArea", value = "出发区(针对直辖市)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endProvince", value = "目的省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endCity", value = "目的城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endArea", value = "目的区(针对直辖市)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "unitPrice", value = "运输单价(元/吨)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "returnUnitPrice", value = "返程单价(元/吨)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "receivePmsg", value = "true接收 false不接收", dataType = "boolean", paramType = "form", required = true),
            @ApiImplicitParam(name = "foward", value = "0正向1反向", dataType = "String", paramType = "form", required = true)

    })
    @ResponseBody
    public String setCarRoad(String openid, String startCity, String endCity,
                             String startProvince, String endProvince,String endArea,String startArea,
                             String unitPrice,
                             String returnUnitPrice,
                             boolean receivePmsg,
                             String foward
    ) {
        log.info("司机设置路线信息(setCarRoad)  openid=" + openid + "|startCity=" + startCity + "|endCity=" + endCity + "|endProvince=" + endProvince + "|startProvince=" + startProvince+"|endArea="+endArea+"|startArea="+startArea);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(unitPrice)) {
            result.setMsg("unitPrice不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisCarRoad logisCarRoad = new LogisCarRoad();
        logisCarRoad.setOpenid(openid);
        if(StrUtil.isNotBlank(startProvince)){
            logisCarRoad.setStartProvince(startProvince);
        }
        if(StrUtil.isNotBlank(endProvince)) {
            logisCarRoad.setEndProvince(endProvince);
        }
        if(StrUtil.isNotBlank(startCity)) {
            logisCarRoad.setStartcity(startCity);
        }
        if(StrUtil.isNotBlank(endCity)) {
            logisCarRoad.setEndcity(endCity);
        }
        if(StrUtil.isNotBlank(endArea)) {
            logisCarRoad.setEndArea(endArea);
        }
        if(StrUtil.isNotBlank(startArea)) {
            logisCarRoad.setStartArea(startArea);
        }
        List<LogisCarRoad> haveList = logisCarRoadService.findList(logisCarRoad);
        if(haveList!=null&&haveList.size()>0){
            result.setMsg("路线重复，添加失败");
            result.setCode(1);
            return this.mapper.toJson(result);
        }

        logisCarRoad.setUnitPrice(unitPrice);
        logisCarRoad.setReturnUnitPrice(returnUnitPrice);
        logisCarRoad.setReceivePmsg(receivePmsg);
        logisCarRoad.setDeliveryCount(0);

        logisCarRoad.setFoward(foward);

        //查询
        LogisFreightPrice searchPrice = new LogisFreightPrice();
        if(StrUtil.isNotBlank(startCity)) {
            searchPrice.setStartCity(startCity);
        }
        if(StrUtil.isNotBlank(endCity)) {
            searchPrice.setEndCity(endCity);
        }
        if(StrUtil.isNotBlank(endArea)){
            searchPrice.setEndArea(endArea);
        }
        List<LogisFreightPrice> logisFreightPrices = logisFreightPriceService.findList(searchPrice);
        int score = 75;
        int price=0;
        if (logisFreightPrices != null && logisFreightPrices.size() > 0) {
            String unitPriceBase = logisFreightPrices.get(0).getUnitPriceBase();
            if(StrUtil.isNotBlank(unitPriceBase)){
                price = Integer.parseInt(unitPriceBase);
                log.info("后台设置的基准价格是 "+price);
            }

        }
        if(price==0){
            Map<String, Double> startMap = BaiduAPI.getLngAndLat(startProvince + startCity);
            Map<String, Double> endMap = BaiduAPI.getLngAndLat(endProvince + endCity);
            String distanceStr = BaiduAPI.getDistance(startMap, endMap);
            if ("0".equals(distanceStr)) {
                distanceStr = BaiduAPI.getDistance(startMap, endMap);
            }
            int distance = Integer.parseInt(distanceStr);
            price = (distance / 10000) * 2;
            if (price < 100) {
                price = price + 20;
            }
            log.info("后台没有设置基准价格,通过距离得出的里程价格是"+price);
        }

        int dif = Integer.parseInt(unitPrice) - price;//差价
        if (dif <= 0 && dif >= -10) {
            score = score + (-dif);//
        }
        if (dif < -10 && dif >= -20) {
            score = 10 + score + (-dif / 2);//
        }
        if (dif < -20 && dif >= -100) {
            score = 20 + score - ((dif + 20) / 10);//
        }
        if (dif < -100) {
            score = 98;//
        }
        if (dif > 0 && dif <= 50) {
            score = score - dif;
        }
        if (dif > 50 && dif <= 150) {
            score = 25 - ((dif - 50) / 5);
        }
        if (dif > 150) {
            score = 9;
        }
        if (score > 100) {
            score = 98;
        }
        if (score < 9) {
            score = 9;
        }
        logisCarRoad.setScore(score);
        logisCarRoad.setRefPrice(price+"");
        logisCarRoadService.save(logisCarRoad);

        LogisCar logisCar = logisCarService.get(logisCarRoad.getOpenid());
        if(logisCar==null){
            result.setMsg("请先进行司机车辆认证");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        logisCar.setRoadCount(logisCar.getRoadCount() + 1);
        logisCarService.save(logisCar);
        logisCarRoadService.save(logisCarRoad);
        LogisDelivery search = new LogisDelivery();
        search.setStartProvince(logisCarRoad.getStartProvince());
        search.setStartCity(logisCarRoad.getStartcity());
        search.setEndProvince(logisCarRoad.getEndProvince());
        search.setEndCity(logisCarRoad.getEndcity());
        search.setStatus("12");
        search.setAuditStatus("1");
        List<LogisDelivery> deliveries = logisDeliveryService.findList(search);
        logisCarRoad.setDeliveryCount(deliveries.size());
        result.setData(logisCarRoad);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "司机修改路线信息")
    @RequestMapping(value = "updateCarRoad", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "编号", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startProvince", value = "出发省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startCity", value = "出发城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startArea", value = "出发区(针对直辖市)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endProvince", value = "目的省", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endCity", value = "目的城市", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "endArea", value = "目的区(针对区)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "unitPrice", value = "运输单价(元/吨)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "returnUnitPrice", value = "返程单价(元/吨)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "receivePmsg", value = "true接收 false不接收", dataType = "boolean", paramType = "form", required = true),
            @ApiImplicitParam(name = "foward", value = "0正向1反向", dataType = "String", paramType = "form", required = true)


    })
    @ResponseBody
    public String updateCarRoad(String id, String openid, String startCity, String endCity,String endArea,String startArea,
                                String startProvince, String endProvince,
                                String unitPrice,
                                String returnUnitPrice,
                                boolean receivePmsg,
                                String foward) {
        log.info("司机修改路线信息(updateCarRoad) id" + id + "|openid=" + openid
                + "|startCity=" + startCity + "|endCity=" + endCity+"|endArea="+endArea
                + "unitPrice=" + unitPrice);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisCarRoad logisCarRoad = logisCarRoadService.get(id);
        if (logisCarRoad != null && (!logisCarRoad.getOpenid().equals(openid))) {
            result.setMsg("您无法修改其他司机的路线");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        logisCarRoad.setOpenid(openid);
        logisCarRoad.setStartProvince(startProvince);
        logisCarRoad.setEndProvince(endProvince);
        logisCarRoad.setStartcity(startCity);
        logisCarRoad.setEndcity(endCity);
        logisCarRoad.setEndArea(endArea);
        logisCarRoad.setStartArea(startArea);
        logisCarRoad.setUnitPrice(unitPrice);
        logisCarRoad.setReturnUnitPrice(returnUnitPrice);
        logisCarRoad.setReceivePmsg(receivePmsg);
        logisCarRoad.setDeliveryCount(0);

        logisCarRoad.setFoward(foward);
        //查询
        LogisFreightPrice searchPrice = new LogisFreightPrice();
        if(StrUtil.isNotBlank(startCity)) {
            searchPrice.setStartCity(startCity);
        }
        if(StrUtil.isNotBlank(endCity)) {
            searchPrice.setEndCity(endCity);
        }
        if(StrUtil.isNotBlank(endArea)){
            searchPrice.setEndArea(endArea);
        }
        List<LogisFreightPrice> logisFreightPrices = logisFreightPriceService.findList(searchPrice);
        int score = 75;
        int price=0;
        if (logisFreightPrices != null && logisFreightPrices.size() > 0) {
            String unitPriceBase = logisFreightPrices.get(0).getUnitPriceBase();
            if(StrUtil.isNotBlank(unitPriceBase)){
                price = Integer.parseInt(unitPriceBase);
                log.info("后台设置的基准价格是 "+price);
            }

        }
        if(price==0){

            Map<String, Double> startMap = BaiduAPI.getLngAndLat(startProvince + startCity);
            Map<String, Double> endMap = BaiduAPI.getLngAndLat(endProvince + endCity);
            String distanceStr = BaiduAPI.getDistance(startMap, endMap);
            if ("0".equals(distanceStr)) {
                distanceStr = BaiduAPI.getDistance(startMap, endMap);
            }
            int distance = Integer.parseInt(distanceStr);
            price = (distance / 10000) * 2;
            if (price < 100) {
                price = price + 20;
            }
            log.info("后台没有设置基准价格,通过距离得出的里程价格是"+price);
        }

        if (StrUtil.isNotBlank(unitPrice)) {
            int dif = Integer.parseInt(unitPrice) - price;//差价 低于市场指导价
            if (dif <= 0 && dif >= -10) {
                score = score + (-dif);//
            }
            if (dif < -10 && dif >= -20) {
                score = 10 + score + (-dif / 2);//
            }
            if (dif < -20 && dif >= -100) {
                score = 20 + score - ((dif + 20) / 10);//
            }
            if (dif < -100) {
                score = 98;//
            }
            if (dif > 0 && dif <= 50) {
                score = score - dif;
            }
            if (dif > 50 && dif <= 150) {
                score = 25 - ((dif - 50) / 5);
            }
            if (dif > 150) {//高于市场价150
                score = 9;
            }
            if (score > 100) {
                score = 98;
            }
            if (score < 9) {
                score = 9;
            }
            logisCarRoad.setScore(score);
        }
        if (StrUtil.isNotBlank(returnUnitPrice)) {
            int dif = Integer.parseInt(returnUnitPrice) - price;//差价 低于市场指导价
            if (dif <= 0 && dif >= -10) {
                score = score + (-dif);//
            }
            if (dif < -10 && dif >= -20) {
                score = 10 + score + (-dif / 2);//
            }
            if (dif < -20 && dif >= -100) {
                score = 20 + score - ((dif + 20) / 10);//
            }
            if (dif < -100) {
                score = 98;//
            }
            if (dif > 0 && dif <= 50) {
                score = score - dif;
            }
            if (dif > 50 && dif <= 150) {
                score = 25 - ((dif - 50) / 5);
            }
            if (dif > 150) {//高于市场价150
                score = 9;
            }
            if (score > 100) {
                score = 98;
            }
            if (score < 9) {
                score = 9;
            }
            logisCarRoad.setReturnScore(score);
        }
        logisCarRoad.setRefPrice(price+"");
        logisCarRoadService.save(logisCarRoad);
        LogisDelivery search = new LogisDelivery();
        search.setStartProvince(logisCarRoad.getStartProvince());
        search.setStartCity(logisCarRoad.getStartcity());
        search.setEndProvince(logisCarRoad.getEndProvince());
        search.setEndCity(logisCarRoad.getEndcity());
        search.setStatus("12");
        search.setAuditStatus("1");
        List<LogisDelivery> deliveries = logisDeliveryService.findList(search);
        logisCarRoad.setDeliveryCount(deliveries.size());
        result.setData(logisCarRoad);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "司机删除路线信息")
    @RequestMapping(value = "deleteCarRoad", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "编号", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String deleteCarRoad(String id, String openid) {
        log.info("司机删除路线信息(deleteCarRoad) id" + id + "|openid=" + openid);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisCarRoad logisCarRoad = logisCarRoadService.get(id);
        if (logisCarRoad != null && (!logisCarRoad.getOpenid().equals(openid))) {
            result.setMsg("您无法删除其他司机的路线");
            result.setCode(1);
            return this.mapper.toJson(result);
        }

        LogisCar logisCar = logisCarService.get(logisCarRoad.getOpenid());
        logisCar.setRoadCount(logisCar.getRoadCount() - 1);
        if (logisCar.getRoadCount() < 0) {
            logisCar.setRoadCount(0);
        }
        logisCarService.save(logisCar);
        logisCarRoadService.delete(logisCarRoad);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "获取司机设置的路线信息")
    @RequestMapping(value = "getCarRoads", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "startCity", value = "出发城市", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "endCity", value = "目的城市", dataType = "String", paramType = "form")
    })
    @ResponseBody
    public String getCarRoads(String openid, String startCity, String endCity) {
        log.info("获取司机设置的路线信息(getCarRoads) openid=" + openid + "|startCity=" + startCity + "|endCity=" + endCity);
        CommonJson result = new CommonJson();
        LogisCarRoad logisCar = new LogisCarRoad();
        if (StringUtils.isNotBlank(openid)) {
            logisCar.setOpenid(openid);
        }
        if (StringUtils.isNotBlank(startCity)) {
            logisCar.setStartcity(startCity);
        }
        if (StringUtils.isNotBlank(endCity)) {
            logisCar.setEndcity(endCity);
        }
        Page<LogisCarRoad> apage = new Page<LogisCarRoad>(1, 100);
        apage.setOrderBy("a.receivePmsg desc,a.startProvince desc, a.startcity desc");
        List<LogisCarRoad> roads = logisCarRoadService.findPage(apage, logisCar).getList();
        List<LogisCarRoad> resultList = Lists.newArrayList();
        for (LogisCarRoad road : roads) {
            LogisDelivery search = new LogisDelivery();
            search.setStartProvince(road.getStartProvince());
            search.setStartCity(road.getStartcity());
            if(StrUtil.isNotBlank(road.getEndProvince())){
                search.setEndProvince(road.getEndProvince());
            }
            if(StrUtil.isNotBlank(road.getEndcity())){
                search.setEndCity(road.getEndcity());
            }
            search.setStatus("12");
            search.setAuditStatus("1");
            List<LogisDelivery> deliveries = logisDeliveryService.findList(search);
            road.setDeliveryCount(deliveries.size());
            resultList.add(road);

//            LogisCarRoad search2 = new LogisCarRoad();
//            search2.setStartProvince(road.getStartProvince());
//            search2.setEndProvince(road.getEndProvince());
//            search2.setStartcity(startCity);
//            search2.setEndcity(endCity);
//            List<LogisCarRoad> logisCarRoads = logisCarRoadService.findList(search2);
//            int score = 80;
//            int count = logisCarRoads.size();
//            if (count > 0) {
//                int insrent = 15 / count;
//                for (LogisCarRoad road2 : logisCarRoads) {
//                    road2.setScore(score);
//                    logisCarRoadService.save(road2);
//                    score = score + insrent;
//                }
//            }
//
        }
        result.setData(resultList);
        //result.setData(roads);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    /**
     * 根据状态获取运单数量
     */
    @ApiOperation(value = "根据状态获取运单数量")
    @RequestMapping(value = "getDeliveryCount", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "deliveryOpenid", value = "发货openid", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "carrierOpenid", value = "司机openid", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "receiverOpenid", value = "收货openid", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "statusIds", value = "物流状态数组",
                    dataType = "String[]", paramType = "query")
    })
    @ResponseBody
    public String getDeliveryCount(String deliveryOpenid, String carrierOpenid, String receiverOpenid, String[] statusIds) {
        CommonJson result = new CommonJson();
        log.info("根据状态获取数量（getDeliveryCount） deliveryOpenid=" + deliveryOpenid + "|carrierOpen=" + carrierOpenid + "|receiverOpenid=" + receiverOpenid);

        LogisDelivery search = new LogisDelivery();
        if (StringUtils.isNotBlank(deliveryOpenid)) {
            search.setCarrier(carrierOpenid);
            LogisUser user = logisUserService.get(carrierOpenid);
            if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
                search.setCarrier(user.getUnionId());
            }
        }
        if (StringUtils.isNotBlank(deliveryOpenid)) {
            search.setOpenid(deliveryOpenid);
            LogisUser user = logisUserService.get(deliveryOpenid);
            if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
                search.setOpenid(user.getUnionId());
            }
        }
        if (StringUtils.isNotBlank(receiverOpenid)) {
            search.setReceiver(receiverOpenid);
            LogisUser user = logisUserService.get(receiverOpenid);
            if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
                search.setReceiver(user.getUnionId());
            }
        }
        if (statusIds != null) {
            search.setStatusIds(statusIds);
        }
        int count = logisDeliveryService.findList(search).size();
        result.setData(count);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 叫车订单数据
     */
    @ApiOperation(value = "叫车订单数据")
    @RequestMapping(value = "getJioacheOrderCount", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query")
    })
    @ResponseBody
    //11已叫车,等待支付订金 ,12已付订金，正在调度司机 13司机接单,运输中,14已卸车, 待结算 15 运输完成 16订单关闭，超时未付款 17调度失败，司机超时未接单 18订单取消，货运计划变更
    public String getJioacheOrderCount(String openid) {
        CommonJson result = new CommonJson();
        log.info("叫车订单数据(getJioacheOrderCount) openid=" + openid);

        LogisDelivery search = new LogisDelivery();
        if (StringUtils.isNotBlank(openid)) {
            search.setOpenid(openid);
            LogisUser user = logisUserService.get(openid);
            if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
                search.setOpenid(user.getUnionId());
            }
        }
        search.setStatusIds(new String[]{"11", "12", "18", "16", "17"});
        int jioacheNum = logisDeliveryService.findList(search).size();
        search.setStatusIds(new String[]{"13"});//13
        int yunszNum = logisDeliveryService.findList(search).size();
        search.setStatusIds(null);
        search.setCarrierStatusIds(new String[]{"34", "35"});
        int daijsNum = logisDeliveryService.findList(search).size();
        search.setCarrierStatusIds(null);
        search.setStatusIds(new String[]{"15"});//
        int yiwcNum = logisDeliveryService.findList(search).size();

        OrderCountVO vo = new OrderCountVO();
        vo.setJioacheNum(jioacheNum);
        vo.setYunszNum(yunszNum);
        vo.setDaijsNum(daijsNum);
        vo.setYiwcNum(yiwcNum);
        result.setData(vo);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 收货订单数据
     */
    @ApiOperation(value = "收货订单数据")
    @RequestMapping(value = "getShouhuoOrderCount", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query")
    })
    @ResponseBody
    public String getShouhuoOrderCount(String openid) {
        CommonJson result = new CommonJson();
        log.info("收货订单数据(getShouhuoOrderCount) openid=" + openid);

        LogisDelivery search = new LogisDelivery();
        if (StringUtils.isNotBlank(openid)) {
            search.setReceiver(openid);
        }
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setReceiver(user.getUnionId());
        }
        search.setStatusIds(new String[]{"11", "12", "18", "16", "17"});
        int jioacheNum = logisDeliveryService.findList(search).size();
        search.setStatusIds(new String[]{"13"});//13
        int yunszNum = logisDeliveryService.findList(search).size();
        search.setStatusIds(null);
        search.setCarrierStatusIds(new String[]{"34", "35"});
        int daijsNum = logisDeliveryService.findList(search).size();
        search.setCarrierStatusIds(null);
        search.setStatusIds(new String[]{"15"});//
        int yiwcNum = logisDeliveryService.findList(search).size();

        OrderCountVO vo = new OrderCountVO();
        vo.setJioacheNum(jioacheNum);
        vo.setYunszNum(yunszNum);
        vo.setDaijsNum(daijsNum);
        vo.setYiwcNum(yiwcNum);
        result.setData(vo);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "更新接收语音提示状态")
    @RequestMapping(value = "updateReceivePmsgStatus", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "receivePmsg", value = "true接收 false不接收", dataType = "boolean", paramType = "form", required = true)
    })
    @ResponseBody
    public String updateReceivePmsgStatus(boolean receivePmsg, String openid) {
        log.info("更新接收语音提示状态 receivePmsg" + receivePmsg + "|openid=" + openid);
        CommonJson result = new CommonJson();

        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisUser user = logisUserService.get(openid);
        user.setReceivePmsg(receivePmsg);
        logisUserService.save(user);
        result.setData(user);
        //log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    /**
     * 获取常见问题
     */
    @ApiOperation(value = "获取常见问题")
    @RequestMapping(value = "getQuestions", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "问题类型(1常见问题 2积分问题)", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "appId", value = "appId", dataType = "String", paramType = "query", required = true),
    })
    @ResponseBody
    public String getQuestions(String type, String appId) {
        CommonJson result = new CommonJson();
        log.info("获取常见问题 type=" + type + "appId=" + appId);
        LogisQuestion search = new LogisQuestion();
        search.setType(type);
        search.setAppId(appId);
        result.setData(logisQuestionService.findList(search));
        log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 我当前未完成的运输单(司机)
     */
    @ApiOperation(value = "我当前未完成的运输单(司机),data为空时表示没有未完成的")
    @RequestMapping(value = "myCurrentCarrier", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String myCurrentCarrier(String openid) {
        CommonJson result = new CommonJson();
        log.info("我当前未完成的运输单 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }

        List<LogisDelivery> deliveries = logisDeliveryService.getMyNoOverCarriers(openid);
        if (deliveries != null && deliveries.size() > 0) {
            LogisDelivery delivery = deliveries.get(0);
            result.setData(delivery);
        }
        // log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    /**
     * 专线合伙人的管理的车辆接单次数
     */
    @ApiOperation(value = "获取专线合伙人的管理的车辆接单次数")
    @RequestMapping(value = "getPartnerOrderCount", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query")
    })
    @ResponseBody
    public String getPartnerOrderCount(String openid) {
        CommonJson result = new CommonJson();
        log.info("获取专线合伙人的管理的车辆接单次数 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisUser search = new LogisUser();
        if (StringUtils.isNotBlank(openid)) {
            search.setShareOpenid(openid);
        }
        List<LogisUser> logisUsers = logisUserService.findList(search);
        int jiedanCount = 0;
        for (LogisUser user : logisUsers) {
            jiedanCount += user.getJiedanNum();
        }
        result.setData(jiedanCount);
        // log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "司机上传装车照片")
    @RequestMapping(value = "driverUploadCarryPics", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "发货单id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "goodsWeight", value = "货物重量(吨)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "goodsVolume", value = "货物体积", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "picPaths", value = "图片数组", dataType = "String[]", paramType = "form")

    })
    @ResponseBody
    public String driverUploadCarryPics(String id,
                                        String openid,
                                        String[] picPaths, String goodsWeight, String goodsVolume) {
        CommonJson result = new CommonJson();
        log.info("司机上传装车照片 id=" + id);

        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisDelivery delivery = logisDeliveryService.get(id);
//        if (!openid.equals(delivery.getCarrier())) {
//            result.setMsg("您不是该运输单的司机，不能上传装车照片");
//            result.setCode(-1);
//            log.info("返回给小程序数据:" + this.mapper.toJson(result));
//            return this.mapper.toJson(result);
//        }
        if (StringUtils.isNotBlank(goodsWeight)) {
            delivery.setGoodsWeight(goodsWeight);
        }
        if (StringUtils.isNotBlank(goodsVolume)) {
            delivery.setGoodsVolume(goodsVolume);
        }
        delivery = logisDeliveryService.driverUploadPics(delivery, picPaths);
        result.setData(delivery);
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "用户提现")
    @RequestMapping(value = "withdrawCash", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "totalAmount", value = "提现金额", dataType = "int", paramType = "form", required = true),
            @ApiImplicitParam(name = "appId", value = "appId", dataType = "int", paramType = "form", required = true)
    })
    @ResponseBody
    public String withdrawCash(String openid, int totalAmount, String appId) {
        log.info("提现 openid=" + openid + "|totalAmount=" + totalAmount + "|appId=" + appId);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(appId)) {
            result.setMsg("appId不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisUser user = this.logisUserService.get(openid);
        if (user == null) {
            result.setCode(-1);
            result.setMsg("用户不存在");
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (totalAmount <= 0) {
            result.setCode(-1);
            result.setMsg("totalAmount参数需大于0");
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (user.getBalance().intValue() < totalAmount) {
            result.setCode(-1);
            result.setMsg("当前账户余额不足");
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }

        EntPayRequest wxEntPayRequest = new EntPayRequest();
        String mchId = wxMpAccountService.get(appId).getMchId();
        wxEntPayRequest.setAppid(appId);
        wxEntPayRequest.setMchId(mchId);
        wxEntPayRequest.setNonceStr(Sha1Util.getNonceStr());
        wxEntPayRequest.setPartnerTradeNo(FlowIdUtil.getInstance().getFlowidNoYear() + "");
        wxEntPayRequest.setOpenid(openid);
        wxEntPayRequest.setCheckName("NO_CHECK");
        wxEntPayRequest.setAmount(totalAmount * 100);
        wxEntPayRequest.setDescription("泉州智慧物流余额提现");
        wxEntPayRequest.setSpbillCreateIp("192.168.0.1");

        try {
            EntPayResult wxEntPayResult = this.wxService.getPayService(appId).getEntPayService().entPay(wxEntPayRequest);
            if ("SUCCESS".equals(wxEntPayResult.getResultCode().toUpperCase())
                    && "SUCCESS".equals(wxEntPayResult.getReturnCode().toUpperCase())) {
                log.info("企业对个人付款成功！\n付款信息：\n" + wxEntPayResult.toString());
                user.setBalance(user.getBalance().subtract(new BigDecimal(totalAmount)));
                logisUserService.save(user);
                GasRecharge recharge = new GasRecharge();
                recharge.setGive(new BigDecimal(totalAmount).multiply(new BigDecimal("-1")));
                recharge.setAmount(new BigDecimal(totalAmount).multiply(new BigDecimal("-1")));
                recharge.setOpenid(openid);
                recharge.setSupportOpenid(openid);//提供的
                recharge.setContent("用户提现");
                recharge.setUnionId(user.getUnionId());
                gasRechargeService.save(recharge);
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            } else {
                log.info("err_code: " + wxEntPayResult.getErrCode()
                        + "  err_code_des: " + wxEntPayResult.getErrCodeDes());
                result.setCode(-1);
                result.setMsg("提现失败!");
                result.setData(wxEntPayResult.getErrCodeDes());
                log.info("返回微信小程序" + mapper.toJson(result));
                return this.mapper.toJson(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg("提现接口出错");
            result.setData(e.getMessage());
            log.info("返回微信小程序" + mapper.toJson(result));
            return this.mapper.toJson(result);
        }


    }

    @Autowired
    private LogisMapLineService logisMapLineService;

    @ApiOperation(value = "上传行车地图经纬度")
    @RequestMapping(value = "uploadMapLine", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "发货单id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "x", value = "经度", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "y", value = "纬度", dataType = "String", paramType = "form")

    })
    @ResponseBody
    public String uploadMapLine(String id, String openid, String x, String y) {
        CommonJson result = new CommonJson();
        log.info("上传经纬度 id=" + id);

        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }

        if (StrUtil.isEmptyOrUndefined(x)) {
            result.setMsg("x经度不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(y)) {
            result.setMsg("y纬度不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisMapLine mapLine = new LogisMapLine();
        mapLine.setDeliveryId(id);
        mapLine.setOpenid(openid);
        mapLine.setX(x);
        mapLine.setY(y);
        logisMapLineService.save(mapLine);
        result.setData(mapLine);
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "获取行车地图")
    @RequestMapping(value = "getMapLine", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "发货单id", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getMapLine(String id) {
        CommonJson result = new CommonJson();
        log.info("获取行车地图 id=" + id);
        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisMapLine mapLine = new LogisMapLine();
        mapLine.setDeliveryId(id);
        result.setData(logisMapLineService.findList(mapLine));
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @Autowired
    private LogisInsurePhotoService logisInsurePhotoService;


    @ApiOperation(value = "司机拍照投保")
    @RequestMapping(value = "insurePhoto", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "deliveryId", value = "发货单id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "pic1", value = "车厢前照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pic2", value = "车厢后照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pic3", value = "车厢左照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pic4", value = "车厢右照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pic5", value = "行驶证照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pic6", value = "行驶证(挂车)照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pic7", value = "驾驶证照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "carHeadPic", value = "车头照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "weightPic", value = "过磅照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "carTailPic", value = "车尾照片", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "morePics", value = "更多细节照片（多张|分隔）", dataType = "String", paramType = "form")

    })
    @ResponseBody
    public String insurePhoto(String deliveryId, String openid, String pic1, String pic2, String pic3,
                              String pic4, String pic5, String pic6, String pic7, String carHeadPic, String weightPic, String carTailPic, String morePics) {
        log.info("拍照投保 openid=" + openid + "|deliveryId=" + deliveryId + "|pic1=" + pic1 + "|pic2=" + pic2 + "|morePics=" + morePics);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(deliveryId)) {
            result.setMsg("deliveryId不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }

        LogisDelivery delivery = logisDeliveryService.get(deliveryId);
        LogisInsurePhoto insurePhoto = logisInsurePhotoService.get(deliveryId);
        if (insurePhoto == null) {
            insurePhoto = new LogisInsurePhoto();
            insurePhoto.setId(deliveryId);
            insurePhoto.setStatus1("0");
            insurePhoto.setStatus2("0");
            insurePhoto.setStatus3("0");
            insurePhoto.setStatus4("0");
            insurePhoto.setStatus5("0");
        }
        insurePhoto.setGoodsName(delivery.getGoodsName());
        insurePhoto.setStartAddress(delivery.getStartProvince() + delivery.getStartCity());
        insurePhoto.setEndAddress(delivery.getEndProvince() + delivery.getEndCity());
        insurePhoto.setDriverName(delivery.getCarrierName());
        insurePhoto.setLicensePlate(delivery.getLicensePlate());
        insurePhoto.setReceiverName(delivery.getReceiverName());
        insurePhoto.setReceiverMobile(delivery.getReceiverMobile());
        insurePhoto.setId(deliveryId);
        insurePhoto.setOpenid(openid);
        insurePhoto.setDeliveryId(deliveryId);
        insurePhoto.setHwbx(delivery.getHwbx());
        insurePhoto.setHwbxText(delivery.getHwbxText());
        if (StringUtils.isNotBlank(pic1)) {
            insurePhoto.setPic1(pic1);
        }
        if (StringUtils.isNotBlank(pic2)) {
            insurePhoto.setPic2(pic2);
        }
        if (StringUtils.isNotBlank(pic3)) {
            insurePhoto.setPic3(pic3);
        }
        if (StringUtils.isNotBlank(pic4)) {
            insurePhoto.setPic4(pic4);
        }
        if (StringUtils.isNotBlank(pic5)) {
            insurePhoto.setPic5(pic5);
        }
        if (StringUtils.isNotBlank(pic6)) {
            insurePhoto.setPic6(pic6);
        }
        if (StringUtils.isNotBlank(pic7)) {
            insurePhoto.setPic7(pic7);
        }
        if (StringUtils.isNotBlank(carHeadPic)) {
            insurePhoto.setCarHeadPic(carHeadPic);
        }
        if (StringUtils.isNotBlank(weightPic)) {
            insurePhoto.setWeightPic(weightPic);
        }
        if (StringUtils.isNotBlank(carTailPic)) {
            insurePhoto.setCarTailPic(carTailPic);
        }
        if (StringUtils.isNotBlank(morePics)) {
            insurePhoto.setMorePics(morePics);
        }
        logisInsurePhotoService.save(insurePhoto);
        result.setData(insurePhoto);
        // log.info("返回微信小程序" + mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "获取投保信息")
    @RequestMapping(value = "getInsurePhoto", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "发货单id", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getInsurePhoto(String id) {
        CommonJson result = new CommonJson();
        log.info("获取投保相片 id=" + id);
        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        result.setData(logisInsurePhotoService.get(id));
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "保险受益人设置")
    @RequestMapping(value = "setBeneficiary", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryId", value = "发货单id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "beneficiary", value = "受益人姓名", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "beneficiaryIdCard", value = "受益人身份证号", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "beneficiaryMobile", value = "收益人手机号", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pic8", value = "发货清单照片（多张|分隔）", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "beneficiaryFinish", value = "信息完整标识(0不完整/1完整)", dataType = "String", paramType = "form")
    })
    @ResponseBody
    public String setBeneficiary(String deliveryId, String beneficiary,
                                 String beneficiaryIdCard, String beneficiaryMobile, String pic8,
                                 String beneficiaryFinish) {
        log.info("保险受益人设置 deliveryId=" + deliveryId +
                "|beneficiary=" + beneficiary + "|beneficiaryIdCard=" + beneficiaryIdCard + "|beneficiaryFinish=" + beneficiaryFinish);
        CommonJson result = new CommonJson();
        if (StrUtil.isEmptyOrUndefined(deliveryId)) {
            result.setMsg("deliveryId不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(beneficiary)) {
            result.setMsg("beneficiary不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        LogisDelivery delivery = logisDeliveryService.get(deliveryId);
        LogisInsurePhoto insurePhoto = logisInsurePhotoService.get(deliveryId);
        if (insurePhoto == null) {
            insurePhoto = new LogisInsurePhoto();
            insurePhoto.setId(deliveryId);
            insurePhoto.setStatus1("0");
            insurePhoto.setStatus2("0");
            insurePhoto.setStatus3("0");
            insurePhoto.setStatus4("0");
            insurePhoto.setStatus5("0");
        }
        insurePhoto.setBeneficiary(beneficiary);
        insurePhoto.setBeneficiaryIdCard(beneficiaryIdCard);
        insurePhoto.setBeneficiaryMobile(beneficiaryMobile);
        insurePhoto.setGoodsName(delivery.getGoodsName());
        insurePhoto.setStartAddress(delivery.getStartProvince() + delivery.getStartCity());
        insurePhoto.setEndAddress(delivery.getEndProvince() + delivery.getEndCity());
        insurePhoto.setDriverName(delivery.getCarrierName());
        insurePhoto.setLicensePlate(delivery.getLicensePlate());
        insurePhoto.setReceiverName(delivery.getReceiverName());
        insurePhoto.setReceiverMobile(delivery.getReceiverMobile());
        insurePhoto.setId(deliveryId);
        //insurePhoto.setOpenid(openid);
        insurePhoto.setDeliveryId(deliveryId);
        insurePhoto.setHwbx(delivery.getHwbx());
        insurePhoto.setHwbxText(delivery.getHwbxText());
        insurePhoto.setPolicyDate(DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
        insurePhoto.setPolicyStartDate(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 1), "yyyy-MM-dd"));
        insurePhoto.setPolicyEndDate(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 9), "yyyy-MM-dd"));
        if (StringUtils.isNotBlank(pic8)) {
            insurePhoto.setPic8(pic8);
        }
        insurePhoto.setBeneficiaryFinish(false);
        if ("1".equals(beneficiaryFinish)) {
            insurePhoto.setBeneficiaryFinish(true);
        }
        logisInsurePhotoService.save(insurePhoto);
        result.setData(insurePhoto);
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);

    }


    @Autowired
    private LogisBxDiscountService logisBxDiscountService;

    @ApiOperation(value = "获取投保优惠信息")
    @RequestMapping(value = "getInsureDiscount", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "保险类别id(1-5)", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getInsureDiscount(String id) {
        CommonJson result = new CommonJson();
        log.info("获取投保优惠信息 id=" + id);
        if (StrUtil.isEmptyOrUndefined(id)) {
            result.setMsg("id不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        result.setData(logisBxDiscountService.get(id));
        // log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "获取全部投保优惠信息")
    @RequestMapping(value = "getAllInsureDiscount", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getAllInsureDiscount() {
        CommonJson result = new CommonJson();
        log.info("获取全部投保优惠信息");
        result.setData(logisBxDiscountService.findList(new LogisBxDiscount()));
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @Autowired
    private LogisMessageService logisMessageService;


    @ApiOperation(value = "我的未读消息数量")
    @RequestMapping(value = "message/unReadCount", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getNoReadMsgCount(String openid) {
        CommonJson result = new CommonJson();
        log.info("获取我的未读消息数量 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisMessage search = new LogisMessage();
        search.setOpenid(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setOpenid(user.getUnionId());
        }
        search.setStatus(0);
        List<LogisMessage> messages = logisMessageService.findList(search);
        result.setData(messages.size());
        log.info(mapper.toJson(result));
        return mapper.toJson(result);
    }

    @ApiOperation(value = "我的消息列表")
    @RequestMapping(value = "message/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getMyMessages(String openid) {
        CommonJson result = new CommonJson();
        log.info("获取我的未读消息数量 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisMessage search = new LogisMessage();
        search.setOpenid(openid);
        LogisUser user = logisUserService.get(openid);
        if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
            search.setOpenid(user.getUnionId());
        }
        search.setStatus(0);
        List<LogisMessage> messages = logisMessageService.findList(search);
        result.setData(messages);
        //log.info(mapper.toJson(result));
        return mapper.toJson(result);
    }

    @ApiOperation(value = "消息详情")
    @RequestMapping(value = "message/detail", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "msgId", value = "消息Id", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String messageInfo(String openid, String msgId) {
        CommonJson result = new CommonJson();
        log.info("获取我的未读消息数量 openid=" + openid);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(msgId)) {
            result.setMsg("msgId不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisMessage message = logisMessageService.get(msgId);
        if (message != null) {
            message.setStatus(1);
            logisMessageService.save(message);
        }
        result.setData(message);
        // log.info(mapper.toJson(result));
        return mapper.toJson(result);
    }


    @Autowired
    private LogisFreightPriceService logisFreightPriceService;


    @ApiOperation(value = "获取两城市间运输单价")
    @RequestMapping(value = "freightUnitPrice/get", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startCity", value = "出发城市", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "startArea", value = "出发区", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "endCity", value = "目的城市", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "endArea", value = "目的区", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "类型(1整车 2零担)", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getFreightPrice(String startCity, String endCity,String endArea,  String type,String startArea) {
        CommonJson result = new CommonJson();
        log.info("获取两城市间运输单价 startCity=" + startCity + "|endCity=" + endCity+"|endArea="+endArea+"|startArea="+startArea);
        if (StrUtil.isEmptyOrUndefined(startCity)) {
            result.setMsg("startCity不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(endCity)) {
            result.setMsg("endCity不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(type)) {
            result.setMsg("type不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisFreightPrice search = new LogisFreightPrice();
        search.setStartCity(startCity);
        search.setEndCity(endCity);
        if(StrUtil.isNotBlank(endArea)){
            search.setEndArea(endArea);
        }
        if(StrUtil.isNotBlank(startArea)){
            search.setStartArea(startArea);
        }
        List<LogisFreightPrice> logisFreightPrices = logisFreightPriceService.findList(search);
        if(logisFreightPrices==null||logisFreightPrices.size()==0){
            search.setEndArea(null);
            logisFreightPrices = logisFreightPriceService.findList(search);
        }
        if (logisFreightPrices != null && logisFreightPrices.size() > 0) {
            result.setData(logisFreightPrices.get(0).getUnitPrice());
            if ("2".equals(type)) {
                result.setData(logisFreightPrices.get(0).getUnitPrice2());
            }
        } else {
            search.setStartCity(endCity);
            search.setEndCity(startCity);
            logisFreightPrices = logisFreightPriceService.findList(search);
            if (logisFreightPrices != null && logisFreightPrices.size() > 0) {
                result.setData(logisFreightPrices.get(0).getReturnUnitPrice());
                if ("2".equals(type)) {
                    result.setData(logisFreightPrices.get(0).getReturnUnitPrice2());
                }
            }
        }
        //log.info(mapper.toJson(result));
        return mapper.toJson(result);
    }

    @Autowired
    private LogisCarCountService logisCarCountService;

//    @ApiOperation(value = "获取附近车辆数量")
//    @RequestMapping(value = "getCarCount", method = {RequestMethod.GET, RequestMethod.POST})
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true),
//            @ApiImplicitParam(name = "province", value = "省", dataType = "String", paramType = "query", required = true),
//            @ApiImplicitParam(name = "city", value = "市", dataType = "String", paramType = "query", required = true),
//            @ApiImplicitParam(name = "area", value = "区", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "address", value = "详细地址", dataType = "String", paramType = "query")
//    })
//    @ResponseBody
//    public String getCarCount(String openid,String province,String city,String area,String address) {
//        CommonJson result = new CommonJson();
//        log.info("获取附近车辆数量 openid=" + openid+"|province="+province+"|city="+city+"|area="+area+"|address="+address);
//        if (StrUtil.isEmptyOrUndefined(openid)) {
//            result.setMsg("openid不能为空");
//            result.setCode(-1);
//            log.info("返回给小程序数据:" + this.mapper.toJson(result));
//            return this.mapper.toJson(result);
//        }
//
//        result.setData("0");
//        LogisCarCount search = new LogisCarCount();
//        if(StrUtil.isNotBlank(province)){
//            search.setProvince(province);
//        }
//        if(StrUtil.isNotBlank(city)){
//            search.setCity(city);
//        }
//        if(StrUtil.isNotBlank(area)){
//            search.setArea(area);
//        }
//        if(StrUtil.isNotBlank(address)){
//            search.setAddress(address);
//        }
//        int count = 0;
//        List<LogisCarCount> carCounts = logisCarCountService.findList(search);
//        List<LogisCarCount> resultList = Lists.newArrayList();
//        if(carCounts.size()==0){
//            search.setAddress(null);
//            carCounts = logisCarCountService.findList(search);
//            for(LogisCarCount ccount:carCounts){
//                if(StrUtil.isBlank(ccount.getAddress())){
//                    resultList.add(ccount);
//                }
//            }
//            carCounts = resultList;
//        }
//        if(carCounts.size()==0){
//            search.setArea(null);
//            carCounts = logisCarCountService.findList(search);
//            for(LogisCarCount ccount:carCounts){
//                if(StrUtil.isBlank(ccount.getArea())){
//                    resultList.add(ccount);
//                }
//            }
//            carCounts = resultList;
//        }
//        if(carCounts.size()==0){
//            search.setCity(null);
//            carCounts = logisCarCountService.findList(search);
//            for(LogisCarCount ccount:carCounts){
//                if(StrUtil.isBlank(ccount.getCity())){
//                    resultList.add(ccount);
//                }
//            }
//            carCounts = resultList;
//        }
//
//        for(LogisCarCount carCount:carCounts){
//            count = count+ carCount.getCarCount();
//        }
//        result.setData(count);
//        log.info(mapper.toJson(result));
//        return mapper.toJson(result);
//    }

    @Autowired
    private NewsTypeService newsTypeService;

    @ApiOperation(value = "获取附近车辆数量")
    @RequestMapping(value = "getCarCount", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "province", value = "省", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "city", value = "市", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "area", value = "区", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "详细地址", dataType = "String", paramType = "query")
    })
    @ResponseBody
    public String getCarCount(String openid, String province, String city, String area, String address) {
        CommonJson result = new CommonJson();
        log.info("获取附近车辆数量 openid=" + openid + "|province=" + province + "|city=" + city + "|area=" + area + "|address=" + address);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        result.setData("0");
        NewsType search = new NewsType();
        List<NewsType> carCounts = Lists.newArrayList();
        if (StrUtil.isNotBlank(address)) {
            search.setName(address);
            carCounts = newsTypeService.findList(search);
        }
        if (carCounts.size() == 0 && StrUtil.isNotBlank(area)) {
            search.setName(area);
            carCounts = newsTypeService.findList(search);
            log.info("address查找不到车辆,通过 area=" + area + " 来查找车辆记录数" + carCounts.size());
        }
        if (carCounts.size() == 0 && StrUtil.isNotBlank(city)) {
            search.setName(city);
            carCounts = newsTypeService.findList(search);
            log.info("area查找不到车辆,通过 city=" + city + " 来查找车辆记录数" + carCounts.size());
        }
        if (carCounts.size() == 0 && StrUtil.isNotBlank(province)) {
            search.setName(province);
            carCounts = newsTypeService.findList(search);
            log.info("city查找不到车辆,通过 province=" + province + " 来查找车辆记录数" + carCounts.size());
        }
        int count = 0;
        String lingdanStatus = "0";
        for (NewsType carCount : carCounts) {
            log.info("查找到车辆位置 name=" + carCount.getName() + "  数量" + carCount.getCarCount());
            count = count + carCount.getCarCount();
            lingdanStatus = carCount.getLingdanStatus();
        }
        result.setData(count);
        result.setMsg(lingdanStatus);
        log.info(mapper.toJson(result));
        return mapper.toJson(result);
    }


    public static final String APP_ID = "10576505";
    public static final String API_KEY = "EIeg8vTBY5RDof8hPynA55A5";
    public static final String SECRET_KEY = "9IbrpntjheaBjyRFw5dw5LkZOdxWDWmT";

    /**
     * 身份证上传
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "身份证上传(货主保险)")
    @RequestMapping(value = "upload/idcard", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryId", value = "运单id", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "type", value = "正面 type为1 反面type为2", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String idcard(MultipartFile file, String deliveryId, String type, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("身份证上传开始上传 deliveryId=" + deliveryId + "|type=" + type);
        CommonJson result = new CommonJson();
        result.setData(0);
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "userfiles/idcard/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        if (StringUtils.isBlank(deliveryId)) {
            result.setCode(1);
            result.setMsg("deliveryId参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (StringUtils.isBlank(type)) {
            result.setCode(1);
            result.setMsg("type参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        String accessPath = "";
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;
            accessPath = Global.getConfig("photoUrl") + "/userfiles/idcard/" + fileName + "." + extension;
            result.setData(accessPath);

        }
        log.info("身份证上传成功图片地址=" + destPath);

        if ("1".equals(type)) {//上传的是身份证正面
            AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            // 传入可选参数调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            JSONObject res = client.idcard(destPath, "front", options);
            log.info("识别出身份证信息=" + res.toString());

            String error_msg;
            try {
                error_msg = res.getString("error_msg");
                if (StringUtils.isNotBlank(error_msg)) {
                    result.setCode(2);
                    result.setData(0);

                    result.setMsg("身份证无法识别,请重新上传");
                    log.info("返回数据:" + this.mapper.toJson(result));
                    return mapper.toJson(result);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
            try {
                String imageStatus = res.getString("image_status");
                log.info("imageStatus=" + imageStatus);
                if (!"normal".equals(imageStatus)) {
                    result.setCode(2);
                    result.setData(0);
                    result.setMsg("身份证无法识别,请重新上传");
                } else {
                    JSONObject words_result = res.getJSONObject("words_result");
                    JSONObject clsbdhJson = words_result.getJSONObject("公民身份号码");
                    String beneficiaryIdCard = clsbdhJson.getString("words");
                    JSONObject zzJson = words_result.getJSONObject("姓名");
                    String beneficiary = zzJson.getString("words");


                    LogisInsurePhoto insure = logisInsurePhotoService.get(deliveryId);
                    if (insure == null) {
                        insure = new LogisInsurePhoto();
                        insure.setId(deliveryId);
                    }
                    insure.setIdcardImg1(accessPath);
                    insure.setBeneficiaryIdCard(beneficiaryIdCard);
                    insure.setBeneficiary(beneficiary);
                    logisInsurePhotoService.save(insure);

                    result.setData(insure);
                }
                log.info("返回数据:" + this.mapper.toJson(result));
                return this.mapper.toJson(result);
            } catch (Exception e) {
                result.setCode(2);
                result.setData(0);

                result.setMsg("身份证无法识别,请重新上传");
                log.info("返回数据:" + this.mapper.toJson(result));
                return this.mapper.toJson(result);
            }

        } else {
            LogisInsurePhoto insure = logisInsurePhotoService.get(deliveryId);
            if (insure != null) {
                insure.setIdcardImg2(accessPath);
                logisInsurePhotoService.save(insure);
            }
            result.setData(insure);
        }
        //log.info("返回数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);

    }

    /**
     * 身份证上传
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "身份证上传(司机认证)")
    @RequestMapping(value = "upload/idcard2", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "正面 type为1 反面type为2", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String idcard2(MultipartFile file, String type, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("司机认证身份证上传开始上传 type=" + type);
        CommonJson result = new CommonJson();
        result.setData(0);
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "userfiles/idcard/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;

        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (StringUtils.isBlank(type)) {
            result.setCode(1);
            result.setMsg("type参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        String accessPath = "";
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;
            accessPath = Global.getConfig("photoUrl") + "/userfiles/idcard/" + fileName + "." + extension;
            result.setData(accessPath);

        }
        log.info("身份证上传成功图片地址=" + destPath);

        if ("1".equals(type)) {//上传的是身份证正面
            AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            // 传入可选参数调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            JSONObject res = client.idcard(destPath, "front", options);
            log.info("识别出身份证信息=" + res.toString());

            String error_msg;
            try {
                error_msg = res.getString("error_msg");
                if (StringUtils.isNotBlank(error_msg)) {
                    result.setCode(2);
                    result.setData(0);

                    result.setMsg("身份证无法识别,请重新上传");
                    log.info("返回数据:" + this.mapper.toJson(result));
                    return mapper.toJson(result);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
            try {
                String imageStatus = res.getString("image_status");
                log.info("imageStatus=" + imageStatus);
                if (!"normal".equals(imageStatus)) {
                    result.setCode(2);
                    result.setData(0);
                    result.setMsg("身份证无法识别,请重新上传");
                } else {
                    JSONObject words_result = res.getJSONObject("words_result");
                    JSONObject clsbdhJson = words_result.getJSONObject("公民身份号码");
                    String idCardNo = clsbdhJson.getString("words");
                    JSONObject zzJson = words_result.getJSONObject("姓名");
                    String realName = zzJson.getString("words");


                    clsbdhJson = words_result.getJSONObject("出生");
                    String birthDay = clsbdhJson.getString("words");

                    clsbdhJson = words_result.getJSONObject("住址");
                    String address = clsbdhJson.getString("words");

                    clsbdhJson = words_result.getJSONObject("性别");
                    String sex = clsbdhJson.getString("words");

                    IdcardVO vo = new IdcardVO();
                    vo.setIdCardNo(idCardNo);
                    vo.setRealName(realName);
                    vo.setBirthDay(birthDay);
                    vo.setAddress(address);
                    vo.setGender(sex);
                    vo.setAccessUrl(accessPath);
                    result.setData(vo);
                    return this.mapper.toJson(result);

                }
                log.info("返回数据:" + this.mapper.toJson(result));
                return this.mapper.toJson(result);
            } catch (Exception e) {
                result.setCode(2);
                result.setData(0);

                result.setMsg("身份证无法识别,请重新上传");
                log.info("返回数据:" + this.mapper.toJson(result));
                return this.mapper.toJson(result);
            }

        } else {

            result.setData(accessPath);
        }
        //log.info("返回数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);

    }


    /**
     * 订单状态修改统一接口
     */
    @ApiOperation(value = "订单状态修改统一接口")
    @RequestMapping(value = "deliver/unifiedUpdateStatus", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryId", value = "订单编号", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "openid", value = "openid", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "status", value = "11已叫车,等待支付订金 ,12已付订金，正在调度司机 13司机接单,运输中,14已卸车, 待结算 15 运输完成 16订单关闭，超时未付款 17调度失败，司机超时未接单 18订单取消，货运计划变更", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "receiverStatus", value = "状态 21已设定详细收货地址 22已选择货运保险,23已付定金，对接运输问题,24已支付运费尾款", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "carrierStatus", value = "状态 31司机到达装车地点 32已装车，开始申报保险,33已申报保险,司机出发 34司机到达目的地，准备卸车，35货主已验货，开始卸车 36运费待结算  37 运费已结算", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "insurStatus", value = "状态 41已申报货运险 42货运险审核中 43货运险已受理 44货车出发、保单已生效  45 货主验收、准备卸车(保单失效) 46货主申请保险理赔 47保险理赔审核中  48保险公司给付保险金 49货运险理赔完成", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "appId", value = "appId(用于区分不同小程序)", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "formId", value = "formId(用于下发模板消息) ", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String unifiedUpdateStatus(String deliveryId, String openid,
                                      String status,
                                      String receiverStatus,
                                      String carrierStatus,
                                      String insurStatus,
                                      String appId, String formId) {
        CommonJson result = new CommonJson();
        log.info("统一订单状态修改 deliveryId=" + deliveryId + "| openid=" + openid + "|status=" + status + "|receiverStatus=" + receiverStatus + "|formId=" + formId + "|appId=" + appId);
        if (StrUtil.isEmptyOrUndefined(openid)) {
            result.setMsg("openid不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(appId)) {
            result.setMsg("appId不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        if (StrUtil.isEmptyOrUndefined(status)
                && StrUtil.isEmptyOrUndefined(receiverStatus)
                && StrUtil.isEmptyOrUndefined(carrierStatus)
                && StrUtil.isEmptyOrUndefined(insurStatus)) {
            result.setMsg("状态不能全为空不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }
        LogisDelivery delivery = logisDeliveryService.get(deliveryId);
        if (delivery == null) {
            result.setMsg("订单不存在，操作失败");
            result.setCode(-1);
            return this.mapper.toJson(result);
        }
        LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
        deliveryLog.setOpenid(openid);
        deliveryLog.setDeliveryId(delivery.getId());
        if (StrUtil.isNotBlank(status)) {//订单状态
            deliveryLog.setStatus(status);
            delivery.setStatus(status);
            if ("12".equals(status)) {//已付订金，正在调度司机
                result.setMsg("由wxPayOk接口自动处理");
                return this.mapper.toJson(result);
            }
            if (!"14".equals(status)) {//14已卸车, 待结算
                logisDeliveryLogService.save(deliveryLog);
            }
        }
        if (StrUtil.isNotBlank(receiverStatus)) {//货主
            deliveryLog.setStatus(receiverStatus);
            delivery.setReceiverStatus(receiverStatus);
            if (!"22".equals(delivery.getReceiverStatus()) && !"23".equals(delivery.getReceiverStatus())) {
                logisDeliveryLogService.save(deliveryLog);
            }
            //发给工厂
            String page = "pages/gcDdXq/gcDdXq?deliveryId=" + delivery.getId();
            String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
            String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
            String keyword3 = delivery.getId();
            String keyword4 = delivery.getStatusText();
            String keyword5 = delivery.getRecStatusText();
            String keyword6 = delivery.getCarrierMobile();
            String keyword7 = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
            wxService.sendTemplateMsg(delivery.getAppId(), delivery.getDevOpenid(), page,
                    formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);
        }
        if (StrUtil.isNotBlank(carrierStatus)) {//司机
            deliveryLog.setStatus(carrierStatus);
            logisDeliveryLogService.save(deliveryLog);

            delivery.setCarrierStatus(carrierStatus);
            //发给收货人
            String page = "/pages/hzDd/hzDd?deliveryId=" + delivery.getId() + "&shareOpenid=&shareState=0";
            String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
            String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
            String keyword3 = delivery.getId();
            String keyword4 = delivery.getStatusText();
            String keyword5 = delivery.getCarrierStatusText();
            String keyword6 = "司机接单后更新";
            if (StrUtil.isNotBlank(delivery.getCarrierMobile())) {
                keyword6 = delivery.getCarrierMobile();
            }
            String keyword7 = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
            wxService.sendTemplateMsg(delivery.getAppId(), delivery.getRecOpenid(), page,
                    formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);
        }
        if (StrUtil.isNotBlank(insurStatus)) {//保险状态
            deliveryLog.setStatus(insurStatus);
            logisDeliveryLogService.save(deliveryLog);
            delivery.setInsurStatus(insurStatus);
            //发给收货人
            String page = "/pages/hzDd/hzDd?deliveryId=" + delivery.getId() + "&shareOpenid=&shareState=0";
            String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
            String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
            String keyword3 = delivery.getId();
            String keyword4 = delivery.getStatusText();
            String keyword5 = delivery.getInsurStatusText();
            String keyword6 = "司机接单后更新";
            if (StrUtil.isNotBlank(delivery.getCarrierMobile())) {
                keyword6 = delivery.getCarrierMobile();
            }
            String keyword7 = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
            wxService.sendTemplateMsg(delivery.getAppId(), delivery.getRecOpenid(), page,
                    formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);
        }

        if ("13".equals(status)) {//司机接单
            delivery.setCarrier(openid);
            delivery.setCarOpenid(openid);
            LogisUser user = logisUserService.get(openid);
            if (user != null && StrUtil.isNotBlank(user.getUnionId())) {
                delivery.setCarrier(user.getUnionId());
            }
            delivery.setReceiptTime(new Date());//接单时间
            if (StringUtils.isBlank(delivery.getCarInfo())) {
                LogisCar car = logisCarService.get(openid);
                if (car != null) {
                    delivery.setCarInfo(car.getRemarks());
                }
            }
            LogisUser logisUser = logisUserService.get(openid);
            logisUser.setJiedanNum(logisUser.getJiedanNum() + 1);
            logisUserService.save(logisUser);

            LogisCar car = logisCarService.get(openid);
            if (car != null && car.getCarStatus() == 1) {//已认证
                delivery.setLicensePlate(car.getLicensePlate()+"+"+car.getTrailerLicensePlate());//设置车牌
                delivery.setDriverRealName(car.getRealName());

            }

            //发给收货人
            String page = "/pages/hzDd/hzDd?deliveryId=" + delivery.getId() + "&shareOpenid=&shareState=0";
            String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
            String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
            String keyword3 = delivery.getId();
            String keyword4 = "司机接单,运输中";
            String keyword5 = delivery.getCarrierStatusText();
            String keyword6 = logisUser.getMobile();
            String keyword7 = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
            wxService.sendTemplateMsg(delivery.getAppId(), delivery.getRecOpenid(), page,
                    formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);

        }
        if ("15".equals(status)) {//已完成
            logisDeliveryService.finishDelivery(delivery);

            LogisMessage search = new LogisMessage();
            search.setDeliveryId(deliveryId);
            List<LogisMessage> messages = logisMessageService.findList(search);
            for (LogisMessage message : messages) {
                message.setStatus(1);
                logisMessageService.save(message);
            }

            //发给收货人
            String page = "/pages/hzDd/hzDd?deliveryId=" + delivery.getId() + "&shareOpenid=&shareState=0";
            String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
            String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
            String keyword3 = delivery.getId();
            String keyword4 = "订单已完成";
            String keyword5 = delivery.getCarrierStatusText();
            String keyword6 = delivery.getCarrierMobile();
            String keyword7 = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
            wxService.sendTemplateMsg(delivery.getAppId(), delivery.getRecOpenid(), page,
                    formId, keyword1, keyword2, keyword3, keyword4, keyword5, keyword6, keyword7);
        }

        logisDeliveryService.save(delivery);
        result.setData(logisDeliveryService.get(delivery.getId()));
        return this.mapper.toJson(result);
    }


    /**
     * 推送保险审核消息
     *
     * @param mobile
     * @return
     */
    @ApiOperation(value = "推送保险审核消息")
    @RequestMapping(value = "sendInsureMsg", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryId", value = "订单编号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "mobile", value = "手机号(接收者)", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String sendInsureMsg(String deliveryId, String mobile) {
        CommonJson result = new CommonJson();
        log.info("推送保险审核消息 mobile=" + mobile);
        if (StrUtil.isEmptyOrUndefined(mobile)) {
            result.setMsg("mobile参数不能为空");
            result.setCode(1);
            return this.mapper.toJson(result);
        }
        if (mobile.length() != 11) {
            result.setMsg("手机号长度不正确");
            result.setCode(2);
            return this.mapper.toJson(result);
        }
        Date sendDate = sendCodeMap.get(mobile);
        if (sendDate != null && DateUtils.addMinute(sendDate, 3)
                .after(new Date())) {//3分钟还没到期
            result.setCode(3);
            result.setMsg("验证码已发送，3分钟内有效");
            return this.mapper.toJson(result);
        }
        try {
            AliyunSms.sendMsg2("百灵智慧物流", mobile);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        sendCodeMap.put(mobile, new Date());
        //log.info("返回给小程序数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);
    }


    @ApiOperation(value = "货运加价和优惠的幅度")
    @RequestMapping(value = "getFreightRange", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "distance", value = "距离(公里)", dataType = "String", paramType = "query", required = true)
    })
    @ResponseBody
    public String getFreightRange(int distance) {
        CommonJson result = new CommonJson();
        log.info("货运加价和优惠的幅度");
        result.setData(logisBxDiscountService.findList(new LogisBxDiscount()));
        //log.info(mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    @ApiOperation(value = "设置装车和卸车地址")
    @RequestMapping(value = "setLoadAndUnloadAddress", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryId", value = "订单编号", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "loadAddress", value = "装货地址", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "unLoadAddress", value = "卸货地址", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String setLoadAndUnloadAddress(String deliveryId, String loadAddress,String unLoadAddress) {
        CommonJson result = new CommonJson();
        log.info("设置装车和卸车地址 deliveryId=" + deliveryId+"|loadAddress="+loadAddress+"|unLoadAddress="+unLoadAddress);
        if (StrUtil.isEmptyOrUndefined(deliveryId)) {
            result.setMsg("deliveryId不能为空");
            result.setCode(-1);
            log.info("返回给小程序数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }

        LogisDelivery delivery = logisDeliveryService.get(deliveryId);
        if(StrUtil.isNotBlank(loadAddress)){
            delivery.setLoadAddress(loadAddress);
        }
        if(StrUtil.isNotBlank(unLoadAddress)){
            delivery.setUnloadAddress(unLoadAddress);
        }
        logisDeliveryService.save(delivery);
        result.setData(delivery);
        // log.info(mapper.toJson(result));
        return mapper.toJson(result);
    }


}
